<?php

//linux系统定时任务
//每天0点校正更新时间
//00 00 * * * curl 域名/crontab.php > /dev/null 2>&1
//每5分钟触发一次更新
//*/5 * * * * curl 域名/cron.php > /dev/null 2>&1
//请务必先手动执行一次

if (!defined('IN_TRACKER'))
	die('Hacking attempt!');
require_once("include/bittorrent.php");
require_once($rootpath . 'lang/_target/lang_cleanup.php');

//error_reporting(E_ALL);
function printProgress($msg) {
	echo $msg . '...完成<br />';
	ob_flush();
	flush();
}

//彩票开奖函数，每3天一次
function drawlotteryfun() {
	global $memcache;
	if (!$memcache) {
		require_once "memcache.php";
	}
	$cash = array();
	$cash[1] = 5000000;
	$cash[2] = 500000;
	$cash[3] = 10000;
	$cash[4] = 1000;
	$cash[5] = 0;
	$cash[6] = 0;
	$lasttime = $memcache->get('drawnumtime');
	if ((((int) date('w')) == 5 || ((int) date('w') == 2)) && (((int) date('H')) >= 21) && (((int) date('H')) <= 22) && ((((int) time()) - $lasttime) >= 24 * 3600)) {
		$memcache->set('drawnumtime', (int) time());
		$date = date('Y-m-d', time());
		$num1 = mt_rand(1, 12);
		$num2 = mt_rand(1, 12);
		$num3 = mt_rand(1, 12);
		$num4 = mt_rand(1, 12);
		$num5 = mt_rand(1, 12);
		sql_query("INSERT INTO drawlottery (num1, num2, num3, num4, num5, drawtime) VALUES ('$num1', '$num2', '$num3', '$num4', '$num5', '$date')") or sqlerr(__FILE__, __LINE__);
		$sql = "SELECT MAX(id) FROM drawlottery";
		$res = sql_query($sql);
		$row = mysql_fetch_array($res);
		$drawid = (int) $row['0'];
		$memcache->set('drawid', $drawid + 1);
		sendshoutbox("开奖啦开奖啦，彩票第 $drawid 期选出了[color=red][b] $num1 -- $num2 -- $num3 -- $num4 -- $num5 [/b][/color]五个数字~记名彩票已经发奖了，不记名的快来兑奖吧~分给我一半吧（口水）");

		$sql = "SELECT * FROM lottery WHERE drawid = '" . $drawid . "' AND ownerid != '0'";
		$res = sql_query($sql)or sqlerr(__FILE__, __LINE__);
		while ($row = mysql_fetch_array($res)) {
			$userid = $row['ownerid'];
			$lotteryid = $row['id'];
			$lnum1 = $row['num1'];
			$lnum2 = $row['num2'];
			$lnum3 = $row['num3'];
			$lnum4 = $row['num4'];
			$lnum5 = $row['num5'];
			$multiple = $row['multiple'];
			$level = 6;
			if ($lnum1 == $num1) {
				$level = $level - 1;
			}
			if ($lnum2 == $num2) {
				$level = $level - 1;
			}
			if ($lnum3 == $num3) {
				$level = $level - 1;
			}
			if ($lnum4 == $num4) {
				$level = $level - 1;
			}
			if ($lnum5 == $num5) {
				$level = $level - 1;
			}
			//sendshoutbox("$level ");
			if ($level < 5) {
				$bonus = $cash[$level] * $multiple;
				$sql = "UPDATE users SET seedbonus =seedbonus +" . $bonus . " WHERE id = " . $userid;
				sql_query($sql) or sqlerr(__FILE__, __LINE__);
				sql_query("UPDATE lottery SET isencase ='$level'  WHERE 	id = " . $lotteryid) or sqlerr(__FILE__, __LINE__);
				$date = date('Y-m-d', time());
				sql_query("UPDATE lottery SET encasetime ='" . $date . "'  WHERE id = " . $lotteryid) or sqlerr(__FILE__, __LINE__);
				sendMessage(0, $userid, "恭喜你中奖了", "恭喜你在彩票第 $drawid 期中获得 $level 等奖，获得魔力值 $bonus");
				writeBonusComment($userid, "彩票第 $drawid 期中获得 $level 等奖，获得魔力值 $bonus");
				//sendshoutbox("彩票第 $drawid 期中获得 $level 等奖，获得魔力值 $bonus");
				if ($level <= 4)
					sendshoutbox("有人在彩票第 $drawid 期中了 $level 等奖，获得魔力值 $bonus ！！！！土豪~~快检查一下站内信看看是不是你吧，土豪来做朋友吧！", '', $date + 5);
			}
		}
	}
}

function docleanup($forceAll = 0, $printProgress = FALSE) {
	//require_once(get_langfile_path("cleanup.php",true));
	global $lang_cleanup_target, $lang_functions;
	global $torrent_dir, $signup_timeout, $max_dead_torrent_time, $autoclean_interval_one, $autoclean_interval_two, $autoclean_interval_three, $autoclean_interval_four, $autoclean_interval_five, $invite_timeout, $iniupload_main, $hr, $hrhit, $hrradio, $hrhour, $hrday, $hrstartradio, $newuser, $kstime, $dl, $ul, $sb, $ra, $dltime, $ultime, $tr, $fa, $hrmanage_class, $newusermanage_class, $bump, $bumptime, $bumpaward, $bumptimeaward, $bumptop, $autosticky, $autostickytime, $autoend, $autoendtime, $endfree, $endsticky, $endlimit, $assessment, $assessmentbonus, $assessmentdate, $assessmentdl, $assessmentdltime, $assessmentname, $assessmentradio, $assessmenttime, $assessmenttr, $assessmentul, $assessmentultime, $assessmentmanage, $assessmentstart, $assessmentfa, $claim, $claimmul, $claimtime, $reward, $rewardnum, $rewarduser, $cuxiao, $cuxiaofree;
	global $donortimes_bonus, $perseeding_bonus, $maxseeding_bonus, $tzero_bonus, $nzero_bonus, $bzero_bonus, $l_bonus, $SITENAME, $BASEURL, $SITEEMAIL;
	global $expirehalfleech_torrent, $expirefree_torrent, $expiretwoup_torrent, $expiretwoupfree_torrent, $expiretwouphalfleech_torrent, $expirethirtypercentleech_torrent, $expirenormal_torrent, $hotdays_torrent, $hotseeder_torrent, $halfleechbecome_torrent, $freebecome_torrent, $twoupbecome_torrent, $twoupfreebecome_torrent, $twouphalfleechbecome_torrent, $thirtypercentleechbecome_torrent, $normalbecome_torrent, $deldeadtorrent_torrent;
	global $neverdelete_account, $neverdeletepacked_account, $deletepacked_account, $deleteunpacked_account, $deletenotransfer_account, $deletenotransfertwo_account, $psdlone_account, $psratioone_account, $psdltwo_account, $psratiotwo_account, $psdlthree_account, $psratiothree_account, $psdlfour_account, $psratiofour_account, $psdlfive_account, $psratiofive_account, $putime_account, $pudl_account, $puprratio_account, $puderatio_account, $eutime_account, $eudl_account, $euprratio_account, $euderatio_account, $cutime_account, $cudl_account, $cuprratio_account, $cuderatio_account, $iutime_account, $iudl_account, $iuprratio_account, $iuderatio_account, $vutime_account, $vudl_account, $vuprratio_account, $vuderatio_account, $exutime_account, $exudl_account, $exuprratio_account, $exuderatio_account, $uutime_account, $uudl_account, $uuprratio_account, $uuderatio_account, $nmtime_account, $nmdl_account, $nmprratio_account, $nmderatio_account, $getInvitesByPromotion_class;
	global $enablenoad_advertisement, $noad_advertisement, $ratioless, $autorelease, $robotusers, $hrbonus, $stronghr, $stronghruntil, $stronghr_radio, $stronghr_time;
	global $Cache, $memcache;
	set_time_limit(0);
	ignore_user_abort(1);
	$now = time();

//等级1更新--开始  默认900秒（15分钟）
	$res = sql_query("SELECT value_u FROM avps WHERE arg = 'lastcleantime1'");
	$row = mysql_fetch_array($res);
	if (!$row) {
		sql_query("INSERT INTO avps (arg, value_u, value_i) VALUES ('lastcleantime1', '$now', '$autoclean_interval_one')") or sqlerr(__FILE__, __LINE__);
		return;
	} else {
		sql_query("UPDATE avps SET value_u = '$now', value_i = '$autoclean_interval_one' WHERE arg = 'lastcleantime1'") or sqlerr(__FILE__, __LINE__);
	}

	//更新Peers状态
	$deadtimes = date("Y-m-d H:i:s", deadtime());
	sql_query("DELETE FROM peers WHERE last_action < " . sqlesc($deadtimes)) or sqlerr(__FILE__, __LINE__);
	if ($printProgress) {
		printProgress('更新Peers状态');
	}

	//做种奖励发放
	$res = sql_query("SELECT DISTINCT userid FROM peers WHERE seeder = 'yes'") or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res) > 0) {
		//参数部分--开始
		$pi = 3.141592653589793;
		$timenow = time();
		$sectoweek = 86400 * 7;
		$count = 0;
		$sqrtof2 = sqrt(2);
		$logofpointone = log(0.1);
		$value1 = $logofpointone / $tzero_bonus; //T0
		$value2 = $bzero_bonus * ( 2 / $pi); //B0
		$value3 = $logofpointone / ($nzero_bonus - 1); //N0
		$value4 = $l_bonus; //L
		$A = 0;
		//参数部分--结束
		while ($arr = mysql_fetch_assoc($res)) {
			$torrentres = sql_query("SELECT torrents.added, torrents.size, torrents.seeders, (SELECT COUNT(*) FROM torrents WHERE official = 'yes') AS official FROM torrents LEFT JOIN peers ON peers.torrent = torrents.id WHERE peers.userid = $arr[userid] AND peers.seeder = 'yes'") or sqlerr(__FILE__, __LINE__);
			while ($torrent = mysql_fetch_array($torrentres)) {
				$weeks_alive = ($timenow - strtotime($torrent['added'])) / $sectoweek;
				$gb_size = $torrent['size'] / 1073741824;
				if ($torrent['official'] > 0) {
					$official = $torrent['official'];
				} else {
					$official = 0;
				}
				$temp = (1 - exp($value1 * $weeks_alive)) * $gb_size * (1 + $sqrtof2 * exp($value3 * ($torrent['seeders'] - 1))) + $official * 0.5;
				$A += $temp;
				$count++;
			}
			if ($count > $maxseeding_bonus) {//固定获取魔力值
				$count = $maxseeding_bonus;
			}
			$is_donor = mysql_fetch_array(sql_query("SELECT donor, class FROM users WHERE id = " . $arr['userid'] . ""));
			$class = $is_donor['class'];
			switch ($class) {
				case UC_POWER_USER:
					$rate = "1.15";
					break;
				case UC_ELITE_USER:
					$rate = "1.2";
					break;
				case UC_CRAZY_USER:
					$rate = "1.25";
					break;
				case UC_INSANE_USER:
					$rate = "1.3";
					break;
				case UC_VETERAN_USER:
					$rate = "1.35";
					break;
				case UC_EXTREME_USER:
					$rate = "1.4";
					break;
				case UC_ULTIMATE_USER:
					$rate = "1.45";
					break;
				case UC_NEXUS_MASTER:
					$rate = "1.5";
					break;
				default :
					$rate = "1.1";
			}
			if ($class >= UC_VIP) {
				$rate = "1.6";
			}
			$all_bonus = (($value2 * atan($A / $value4) + ($perseeding_bonus * $count)) * $rate) / (3600 / $autoclean_interval_one);
			if ($is_donor['donor'] == 'yes' && $donortimes_bonus > 0) {
				$all_bonus = $all_bonus * $donortimes_bonus;
			}
			KPS("+", $all_bonus, $arr["userid"]);
		}
	}
	if ($printProgress) {
		printProgress('为做种用户发放奖励');
	}

	//全局促销时效检查
	$globalcheck = mysql_fetch_array(sql_query("SELECT global_sp_state FROM torrents_state"));
	if ($globalcheck['global_sp_state'] != 1) {
		$dt = sqlesc(date("Y-m-d H:i:s", time()));
		sql_query("UPDATE torrents_state SET global_sp_state = 1 WHERE global_endfree < $dt");
		$Cache->delete_value('global_promotion_state');
		if ($printProgress) {
			printProgress("检查全局促销时效");
		}
	}

	//自动发布候选区符合条件的种子
	if ($autorelease == 'yes') {
		$res = sql_query("SELECT id, name, status, seeders, releasedate FROM torrents WHERE status = 'candidate'") or sqlerr(__FILE__, __LINE__);
		if (mysql_num_rows($res) > 0) {
			while ($row = mysql_fetch_array($res)) {
				$beforeStatus = getTorrentStatus($row['status']);
				if ($row['seeders'] > 0 && $row['releasedate'] == '') {//有做种且定时发布为空时
					sql_query("UPDATE torrents SET status = 'normal', added = '" . date("Y-m-d H:i:s", time()) . "' WHERE seeders > 0 AND status = 'candidate'") or sqlerr(__FILE__, __LINE__);
					write_log("系统自动发布：$beforeStatus 种子 $row[id] ($row[name]) 被系统自动发布了 。原因是： (有做种者)", 'normal');
				} elseif ($row['seeders'] > 0 && $row['releasedate'] == date("Y-m-d", time())) {//当前日期与定时发布相同
					sql_query("UPDATE torrents SET status = 'normal', added = '" . date("Y-m-d H:i:s", time()) . "' WHERE seeders > 0 AND status = 'candidate' AND releasedate = '" . $row['releasedate'] . "'") or sqlerr(__FILE__, __LINE__);
					write_log("系统自动发布：$beforeStatus 种子 $row[id] ($row[name]) 被系统自动发布了 。原因是： (有做种者且定时在 $row[releasedate] 发布)", 'normal');
				}
			}
		}
		if ($printProgress) {
			printProgress("发布候选区有做种的种子，或有做种的且定时发布的种子");
		}
	}
//等级1更新--结束
//等级2更新--开始  默认1800秒（30分钟）
	$res = sql_query("SELECT value_u FROM avps WHERE arg = 'lastcleantime2'");
	$row = mysql_fetch_array($res);
	if (!$row) {
		sql_query("INSERT INTO avps (arg, value_u, value_i) VALUES ('lastcleantime2', '$now', '$autoclean_interval_two')") or sqlerr(__FILE__, __LINE__);
		return;
	}
	$ts = $row[0];
	if ($ts + $autoclean_interval_two > $now && !$forceAll) {
		return '等级2的清理已完成';
	} else {
		sql_query("UPDATE avps SET value_u = '$now', value_i = '$autoclean_interval_two' WHERE arg = 'lastcleantime2'") or sqlerr(__FILE__, __LINE__);
	}

	//更新种子可见状态
	$deadtime = deadtime() - $max_dead_torrent_time;
	sql_query("UPDATE torrents SET visible = 'no' WHERE visible = 'yes' AND last_action < FROM_UNIXTIME($deadtime) AND seeders = 0") or sqlerr(__FILE__, __LINE__);
	if ($printProgress) {
		printProgress("更新种子可见状态");
	}

	//回收红包剩余魔力值
	$deltime = date("Y-m-d H:i:s", time() - 86400);
	$res = sql_query("SELECT * FROM gift WHERE date <= '$deltime' AND lose = 'no'") or sqlerr(__FILE__, __LINE__); //取出所有添加时间<=一天前的数据
	while ($row = mysql_fetch_array($res)) {
		$bonus = mysql_fetch_array(sql_query("SELECT SUM(bonus) AS bonus FROM giftlog WHERE cards = '$row[cards]'")); //取出该红包所有已经被领取的魔力值
		$getbonus = $row['bonus'] - $bonus['bonus']; //计算该红包剩余魔力值
		sql_query("UPDATE users SET seedbonus = seedbonus + $getbonus WHERE id = $row[userid]");
		sql_query("UPDATE gift SET lose = 'yes' WHERE date <= '$deltime' AND lose = 'no'");
		writeBonusComment($row['userid'], "收回红包 $row[cards] 没有被领取的剩余 $getbonus 个魔力值");
	}
	if ($printProgress) {
		printProgress("回收红包剩余魔力值");
	}

	//清除已删除充值卡的充值记录
	sql_query("DELETE FROM rechargelog WHERE cards NOT IN (SELECT cards FROM recharge)");
	if ($printProgress) {
		printProgress("清除已删除充值卡的充值记录");
	}

	//每6小时解除被自动封禁的IP
	$deltime = date("Y-m-d H:i:s", time() - 3600 * 6);
	sql_query("DELETE FROM loginattempts WHERE banned = 'yes' AND added <= '$deltime'");
	if ($printProgress) {
		printProgress("解除被自动封禁的IP");
	}

	//自动机器人回收发布超过15天的断种美剧
	$deltime = date("Y-m-d H:i:s", time() - 86400 * 15);
	$timestamp = sqlesc(date("Y-m-d H:i:s"));
	sql_query("UPDATE torrents SET banned = 'yes', visible = 'no' ,status = 'recycle', last_status = $timestamp, added =$timestamp FROM torrents WHERE seeders = 0 AND visible = 'yes' AND banned = 'no' AND category = 402 AND source = 25 AND owner = $robotusers AND added <= '$deltime'");
	if ($printProgress) {
		printProgress("回收机器人发布超过15天的断种美剧");
	}

	//自动取消救活后2小时无下载者的置顶状态种子
	$deltime = date("Y-m-d H:i:s", time() - 3600 * 2);
	sql_query("UPDATE torrents SET pos_state = 'normal' WHERE bumpoff = 'yes' AND last_action <= '$deltime'");
	if ($printProgress) {
		printProgress("取消救活后2小时无下载者的置顶状态种子");
	}

	//自动清理过期短信
	if (time() > 1323069888 + 604800) {
		$deltime = date("Y-m-d H:i:s", time() - 2592000); //一个月前时间
		sql_query("DELETE FROM messages WHERE location = 1 AND added < '" . $deltime . "'") or sqlerr(__FILE__, __LINE__);
	}
	if ($printProgress) {
		printProgress("清理过期短信");
	}

	//将超过三天未登录用户重置salarynum
	$deltime = date("Y-m-d", time() - 86400 * 3);
	$res = sql_query("SELECT id FROM users WHERE  salarynum > 1 AND salary < '" . $deltime . "'") or sqlerr(__FILE__, __LINE__);
	while ($row = mysql_fetch_assoc($res)) {
		sql_query("UPDATE users SET salarynum = 1 WHERE id = $row[id]") or sqlerr(__FILE__, __LINE__);
	}

	if ($printProgress) {
		printProgress("重置超过三天未登录用户的连续登录天数");
	}

	//自动清理过期的回收站、候选区种子
	$deltime = date("Y-m-d H:i:s", time() - 86400 * 30); //默认30天
	$res = sql_query("SELECT id, name, status, owner, url, dburl FROM torrents WHERE status != 'normal' AND last_status < '" . $deltime . "'") or sqlerr(__FILE__, __LINE__);
	while ($row = mysql_fetch_array($res)) {
		deletetorrent($row['id'], $row['url'], $row['dburl']);
		$beforeStatus = getTorrentStatus($row['status']);
		sendMessage(0, $row['owner'], "你在回收站里的种子被删除了", "系统自动清理：$beforeStatus 种子 $row[id] ($row[name]) 被系统自动删除了 。原因是： (30天未处理)");
		write_log("系统自动清理：$beforeStatus 种子 $row[id] ($row[name]) 被系统自动删除了 。原因是： (30天未处理)", 'normal');
	}
	if ($printProgress) {
		printProgress("清理扔进回收站30天的种子");
	}

	//自动清理无下载动作的记录开始
	/*
	  $deltime = date("Y-m-d H:i:s", time() - 86400 * 1);
	  sql_query("DELETE FROM snatched WHERE finished = 'no' AND last_action < '" . $deltime . "'") or sqlerr(__FILE__, __LINE__);
	  if ($printProgress) {
	  printProgress("无下载动作的记录已清理");
	  }
	 * 会导致总做种或下载时间不对，弃用！！！
	 */

	//彩票开奖
	drawlotteryfun();
	if ($printProgress) {
		printProgress("彩票开奖");
	}

	//BUMP
	/*
	 * 断种超过$bumptime的触发BUMP
	 * 所有给触发BUMP的种子做种的都将得到奖励
	 */
	if ($bump == 'yes') {
		$pi = 3.141592653589793;
		$sqrtof2 = sqrt(2);
		$logofpointone = log(0.1);
		$value1 = $logofpointone / $tzero_bonus; //T0
		$value2 = $bzero_bonus * ( 2 / $pi); //B0
		$value3 = $logofpointone / ($nzero_bonus - 1); //N0
		$value4 = $l_bonus; //L
		$bumpchecktime = sqlesc(date("Y-m-d H:i:s", (deadtime() - $bumptime * 86400))); //超时时间
		$bumpchecktop = sqlesc(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " + " . $bumptop . " days"))); //置顶并促销
		if ($bump == 'yes') {
			sql_query("UPDATE torrents SET bumptime = 'yes' WHERE last_action < $bumpchecktime AND added < $bumpchecktime AND seeders = '0' AND visible = 'no' AND banned = 'no'"); //标记最后更新时间、添加时间<指定BUMP天数的，且做种数为0，显示且未被BAN的
			$res = sql_query("SELECT id, name, added, size, seeders FROM torrents WHERE seeders > 0 AND bumptime = 'yes'"); //取出触发BUMP且做种数>0的种子信息
			while ($row = mysql_fetch_assoc($res)) {
				$size = $row['size'] / 1073741824;
				$offtorrents = (time() - strtotime($row['added'])) / 86400 * 7;
				$A = (1 - exp($value1 * $offtorrents)) * $size * (1 + $sqrtof2 * exp($value3 * $row['seeders'])); //变量
				if ($A != 0) {//公式
					$all_bonus = ($value2 * atan($A / $value4)) + $bumpaward + (1 + log($bumptimeaward));
				} else {
					$all_bonus = $bumpaward + (1 + log($bumptimeaward));
				}
				$userinfo = mysql_fetch_array(sql_query("SELECT userid FROM peers WHERE torrent = " . $row['id'] . " AND seeder = 'yes'")); //取出该种子做种的用户ID
				$bumpbonus = round(($all_bonus), 2); //BUMP积分奖励
				if ($userinfo['userid'] != '') {
					sql_query("UPDATE users SET seedbonus = seedbonus + $bumpbonus WHERE id = " . $userinfo['userid']) or sqlerr(__FILE__, __LINE__); //结算
					writeBonusComment($userinfo['userid'], "因种子： " . $row['id'] . " [" . $row['name'] . "] 的BUMP增加 $bumpbonus 个魔力值");
					sendMessage(0, $userinfo['userid'], "BUMP奖励", "因种子： " . $row['id'] . " [" . $row['name'] . "] 的BUMP增加 $bumpbonus 个魔力值");
				}
				if (!empty($bumptop)) {
					if ($ratioless == 'no') {
						sql_query("UPDATE torrents SET bumpoff = 'yes', pos_state = 'sticky', endsticky = $bumpchecktop, sp_state = '2', endfree = $bumpchecktop WHERE id = " . $row['id']) or sqlerr(__FILE__, __LINE__);
					} else {
						sql_query("UPDATE torrents SET bumpoff = 'yes', pos_state = 'sticky', endsticky = $bumpchecktop, sp_state = '3', endfree = $bumpchecktop WHERE id = " . $row['id']) or sqlerr(__FILE__, __LINE__);
					}
					write_log("种子：" . $row['id'] . " [" . $row['name'] . "] 因BUMP置顶并免费(促销)，直到" . $bumpchecktop);
				}
				sql_query("UPDATE torrents SET bumptime = 'no' WHERE id = " . $row['id']) or sqlerr(__FILE__, __LINE__);
			}
		}
		if ($printProgress) {
			printProgress("检查BUMP");
		}
	}

	//限时显示禁区
	$onlimitdate = sqlesc(date("Y-m-d H:i:s", time() - 86400 * 1));
	$a = sql_query("SELECT id FROM users WHERE onlimit = 'yes' AND onlimitdate < $onlimitdate");
	while ($row = mysql_fetch_assoc($a)) {
		sql_query("UPDATE users SET onlimit = 'no', onlimitdate = '0000-00-00 00:00:00' WHERE id = " . $row['id']);
	}
	if ($printProgress) {
		printProgress("清理超过24小时的开启禁区行为");
	}

	//邀请人奖励
	/*
	 * 1、每月1号结算
	 * 2、清空表并初始化数据
	 */
	$lasttime = $memcache->get('udlog');
	if (((int) date('d') == 1) && ((int) date('H') >= 0) && ((int) date('H') <= 1) && ((((int) time()) - $lasttime) >= 24 * 3600)) {//每个月1号凌晨0点到1点之间结算
		$memcache->set('udlog', (int) time());
		$io = sql_query("SELECT id, class, invited_by, uploaded, downloaded, seedtime, leechtime, seedbonus FROM users WHERE enabled = 'yes'");
	}
	while ($row = mysql_fetch_array($io)) {
		$userid = $row['id'];
		//结算--开始
		$formeruploaded = mysql_fetch_array(sql_query("SELECT SUM(uploaded) AS uploaded FROM users WHERE class < $rewarduser AND  invited_by = $userid")); //统计该邀请人所有<$rewarduser的后宫当前的上传量
		$rewarduploaded = mysql_fetch_array(sql_query("SELECT SUM(uploaded) AS uploaded FROM udlog WHERE class < $rewarduser AND invited_by = $userid")); //统计该邀请人所有<$rewarduser的后宫月初1号的上传量
		$spikeuploaded = (0 + $formeruploaded['uploaded']) - (0 + $rewarduploaded['uploaded']); //统计该邀请人所有后宫的上传增量
		$big = $spikeuploaded * $reward / 10000000000; //逼格，百亿分之$reward
		if ($big < 10000) {
			sql_query("UPDATE users SET big = big + $big WHERE id = $userid");
			writecomment($userid, "获得 $big 个荣誉值(封顶 10000)");
		} else {
			sql_query("UPDATE users SET big = big + 10000 WHERE id = $userid");
			writecomment($userid, "获得 10000 个荣誉值(封顶 10000)");
		}
		if (!empty($rewardnum)) {//如果非空或非0
			if ($spikeuploaded <= $rewardnum) {
				sql_query("UPDATE users SET uploaded = uploaded + $spikeuploaded * $reward / 100 WHERE id = $userid"); //符合条件则用统计的增量数值结算
				writecomment($userid, "得到上个月你所有后宫上传量的 $reward %，总计" . mksize($spikeuploaded * $reward / 100) . " (封顶 " . mksize($rewardnum) . " 的 {$reward}%)");
			} else {
				sql_query("UPDATE users SET uploaded = uploaded + $rewardnum * $reward / 100 WHERE id = $userid"); //否则用最大值结算
				writecomment($userid, "得到上个月你所有后宫上传量的 $reward %，总计" . mksize($rewardnum * $reward / 100) . " (封顶 " . mksize($rewardnum) . " 的 {$reward}%)");
			}
		} else {
			sql_query("UPDATE users SET uploaded = uploaded + $spikeuploaded * $reward / 100 WHERE id = $userid"); //不封顶结算
			writecomment($userid, "得到上个月你所有后宫上传量的 $reward %，总计" . mksize($spikeuploaded * $reward / 100) . "");
		}
		//结算--结束
		//sql_query("TRUNCATE TABLE udlog"); //清空表
		$checkud = sql_query("SELECT id FROM udlog WHERE userid = $userid");
		if (mysql_num_rows($checkud) == 0) {//有记录的更新数据，没记录的初始化数据
			sql_query("INSERT INTO udlog (userid, class, invited_by, uploaded, downloaded, seedtime, leechtime, seedbonus, date) VALUE ('" . $userid . "', '" . $row['class'] . "', '" . $row['invited_by'] . "', '" . $row['uploaded'] . "', '" . $row['downloaded'] . "', '" . $row['seedtime'] . "', '" . $row['leechtime'] . "', '" . $row['seedbonus'] . "', '" . date("Y-m-d", time()) . "')") or sqlerr(__FILE__, __LINE__); //初始化数据
		} else {
			sql_query("UPDATE udlog SET uploaded = $row[uploaded], downloaded = $row[downloaded], seedtime = $row[seedtime], leechtime = $row[leechtime], seedbonus = $row[seedbonus], class = $row[class], date = '" . date("Y-m-d", time()) . "' WHERE userid = $userid") or sqlerr(__FILE__, __LINE__); //更新数据
		}
		if ($printProgress) {
			printProgress("统计会员上个月下载量、上传量、做种时间、下载时间及魔力值增量并结算邀请人奖励");
		}
	}

	sql_query("DELETE FROM udlog WHERE userid NOT IN (SELECT id FROM users WHERE enabled = 'yes')") or sqlerr(__FILE__, __LINE__); //清理被禁或不存在的帐号信息
	sql_query("DELETE FROM udlog WHERE invited_by NOT IN (SELECT id FROM users WHERE enabled = 'yes')") or sqlerr(__FILE__, __LINE__); //清理邀请人被禁的帐号信息
	//清理被禁用或不存在帐号的认领和小货车
	sql_query("DELETE FROM claim WHERE userid NOT IN (SELECT id FROM users WHERE enabled = 'yes')");
	sql_query("DELETE FROM truckmarks WHERE userid NOT IN (SELECT id FROM users WHERE enabled = 'yes')");
	if ($printProgress) {
		printProgress("清理被禁用帐号的认领和小货车");
	}

	//判断种子促销
	function torrent_promotion_expire($days, $type = 2, $targettype = 1) {
		$secs = (int) ($days * 86400); //XX days
		$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - ($secs))));
		$res = sql_query("SELECT id, name FROM torrents WHERE added < $dt AND sp_state = " . sqlesc($type) . ' AND promotion_time_type = 0') or sqlerr(__FILE__, __LINE__);
		switch ($targettype) {
			case 1: //normal
				{
					$sp_state = 1;
					$become = "普通";
					break;
				}
			case 2: //Free
				{
					$sp_state = 2;
					$become = "Free";
					break;
				}
			case 3: //2x
				{
					$sp_state = 3;
					$become = "2x";
					break;
				}
			case 4: //2xFree
				{
					$sp_state = 4;
					$become = "2xFree";
					break;
				}
			case 5: //50% Leech
				{
					$sp_state = 5;
					$become = "50%";
					break;
				}
			case 6: //2x50% Leech
				{
					$sp_state = 6;
					$become = "2x50%";
					break;
				}
			case 7: //30% Leech
				{
					$sp_state = 7;
					$become = "30%";
					break;
				}
			default: //normal
				{
					$sp_state = 1;
					$become = "普通";
					break;
				}
		}
		while ($arr = mysql_fetch_assoc($res)) {
			sql_query("UPDATE torrents SET sp_state = $sp_state, endfree = '0000-00-00 00:00:00' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
			if ($sp_state != 1)
				write_log("种子： $arr[id] ($arr[name]) 的促销被系统自动改为 $become", 'normal');
		}
	}

	if ($expirehalfleech_torrent)
		torrent_promotion_expire($expirehalfleech_torrent, 5, $halfleechbecome_torrent);
	if ($expirefree_torrent)
		torrent_promotion_expire($expirefree_torrent, 2, $freebecome_torrent);
	if ($expiretwoup_torrent)
		torrent_promotion_expire($expiretwoup_torrent, 3, $twoupbecome_torrent);
	if ($expiretwoupfree_torrent)
		torrent_promotion_expire($expiretwoupfree_torrent, 4, $twoupfreebecome_torrent);
	if ($expiretwouphalfleech_torrent)
		torrent_promotion_expire($expiretwouphalfleech_torrent, 6, $twouphalfleechbecome_torrent);
	if ($expirethirtypercentleech_torrent)
		torrent_promotion_expire($expirethirtypercentleech_torrent, 7, $thirtypercentleechbecome_torrent);
	if ($expirenormal_torrent)
		torrent_promotion_expire($expirenormal_torrent, 1, $normalbecome_torrent);

	sql_query("UPDATE torrents SET sp_state = 1, promotion_time_type = 0, promotion_until = '0000-00-00 00:00:00' WHERE promotion_time_type = 2 AND promotion_until < " . sqlesc(date("Y-m-d H:i:s", TIMENOW))) or sqlerr(__FILE__, __LINE__);
	if ($printProgress) {
		printProgress("判断种子促销截止日期");
	}

	//自动Free结束后改为随机促销
	if ($cuxiao == 'yes' && $ratioless == 'no') {
		$res = sql_query("SELECT id, sp_state FROM torrents WHERE endfree - added = {$cuxiaofree}000000") or sqlerr(__FILE__, __LINE__);
		if (mysql_num_rows($res) > 0) {
			while ($row = mysql_fetch_assoc($res)) {
				$randsp = mt_rand(2, 7);
				if ($row['sp_state'] == 1) {
					sql_query("UPDATE torrents SET sp_state = $randsp, endfree = '0000-00-00 00:00:00' WHERE id = $row[id]") or sqlerr(__FILE__, __LINE__);
				}
			}
		}
		if ($printProgress) {
			printProgress("新发布自动促销结束转随机促销");
		}
	}

	//判断热门种子
	if ($hotdays_torrent) {
		$secs = (int) ($hotdays_torrent * 86400); //XX days
		$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - ($secs))));
		sql_query("UPDATE torrents SET picktype = 'hot' WHERE added > $dt AND picktype = 'normal' AND seeders > " . sqlesc($hotseeder_torrent)) or sqlerr(__FILE__, __LINE__);
	}
	if ($printProgress) {
		printProgress("判断种子是否热门");
	}

	//无做种的置顶自动取消
	if ($autosticky == 'yes') {
		$deltime = date("Y-m-d H:i:s", time() - 86400 * $autostickytime);
		$res = sql_query("SELECT id, name FROM torrents WHERE seeders = '0' AND (pos_state = 'sticky' OR marrow = 'marrow') AND added < '$deltime'") or sqlerr(__FILE__, __LINE__);
		if (mysql_num_rows($res) > 0) {
			while ($row = mysql_fetch_assoc($res)) {
				sql_query("UPDATE torrents SET pos_state = 'normal', marrow = 'normal' WHERE id = " . $row['id']) or sqlerr(__FILE__, __LINE__);
				write_log("种子：" . $row['id'] . " " . $row['name'] . " 因发布" . $autostickytime . "天后无做种者被取消置顶");
			}
		}
		if ($printProgress) {
			printProgress("取消发布" . $autostickytime . "天后无做种的置顶");
		}
	}

	//系统随机选取并促销（置顶）
	if ($autoend == 'yes') {
		$lastwheretime = $memcache->get('wheretime');
		$res = sql_query("SELECT id, name, sp_state, pos_state, endfree, endsticky FROM torrents WHERE pos_state = 'normal' AND seeders > '0' AND banned = 'no' AND visible = 'yes' AND id >= (SELECT FLOOR(MAX(id) * RAND()) FROM torrents) ORDER BY id LIMIT $endlimit") or sqlerr(__FILE__, __LINE__);
		if (((((int) time()) - $lastwheretime) >= 86400 * $autoendtime)) {
			$memcache->set('wheretime', (int) time());
			while ($rand = mysql_fetch_assoc($res)) {
				$sprand = mt_rand(2, 7);
				if (!empty($endfree) && $rand['sp_state'] == 1 && $ratioless == 'no') {//如果$endfree不为0或空，促销代码为1，并且未开启RatioLess，则随机促销
					$updateset[] = "sp_state = $sprand";
					$updateset[] = "endfree = '" . date("Y-m-d H:i:s", time() + 86400 * $endfree) . "'";
					sql_query("UPDATE torrents SET " . join(",", $updateset) . " WHERE id = " . $rand['id']) or sqlerr(__FILE__, __LINE__);
					write_log("种子：" . $rand['id'] . " " . $rand['name'] . " 被系统随机选取并促销 " . $endfree . " 天");
				}
				if (!empty($endsticky)) {
					$updateset[] = "pos_state = 'sticky'";
					$updateset[] = "endsticky = '" . date("Y-m-d H:i:s", time() + 86400 * $endsticky) . "'";
					sql_query("UPDATE torrents SET " . join(",", $updateset) . " WHERE id = " . $rand['id']) or sqlerr(__FILE__, __LINE__);
					write_log("种子：" . $rand['id'] . " " . $rand['name'] . " 被系统随机选取并置顶 " . $endsticky . " 天");
				}
			}
		}
		if ($printProgress) {
			printProgress("随机促销或置顶");
		}
	}

	//清理过期限时邀请
	$deltime = sqlesc(date("Y-m-d", time() + 86400 * 1)); //限时邀请过期时间+1
	$res = sql_query("SELECT * FROM limitinvite WHERE limited < $deltime AND userid IN (SELECT id FROM users WHERE enabled = 'yes')") or sqlerr(__FILE__, __LINE__);
	while ($row = mysql_fetch_assoc($res)) {
		$checkinvite = mysql_fetch_array(sql_query("SELECT invites FROM users WHERE id = " . $row['userid'])) or sqlerr(__FILE__, __LINE__);
		if ($checkinvite['invites'] > 0) {//优先删除发放的限时邀请
			sql_query("UPDATE users SET invites = invites - " . $row['invites'] . " WHERE id = " . $row['userid']) or sqlerr(__FILE__, __LINE__);
		}
		sql_query("DELETE FROM limitinvite WHERE limited < $deltime") or sqlerr(__FILE__, __LINE__);
	}
	if ($printProgress) {
		printProgress("清理过期限时邀请");
	}

	//小货车自动清理
	$truckdt = sqlesc(date("Y-m-d", time() - 86400 * 10));
	sql_query("DELETE FROM truckmarks WHERE added < $truckdt");
	if ($printProgress) {
		printProgress("清理加入小货车10天以上的种子");
	}

	//认领种子
	/*
	 * 每个月1号检查认领时间是否超过30天
	 * 如果超过30天，则释放
	 * 如果没超过30天，则保留
	 * 未达标的且未超过30天的结算完重置，超过30天的结算完释放；达标的释放
	 */
	if ($claim == 'yes') {
		$dt = date("Y-m-d", (TIMENOW - 30 * 86400)); //默认30天
		$lasttime = $memcache->get('claimtime');
		if (((int) date('d') == 1) && ((int) date('H') >= 0) && ((int) date('H') <= 1) && ((((int) time()) - $lasttime) >= 24 * 3600)) {//每个月1号凌晨0点到1点之间结算
			$memcache->set('claimtime', (int) time());
			$claimres = sql_query("SELECT * FROM claim ORDER BY id DESC");
		}
		while ($row = mysql_fetch_array($claimres)) {
			$userid = $row['userid'];
			$torrentid = $row['torrentid'];
			$torrentres = mysql_fetch_array(sql_query("SELECT size, name FROM torrents WHERE id = $torrentid"));
			$torrentsize = $torrentres['size'];
			$torrent_name = $torrentres['name'];
			$snat = mysql_fetch_array(sql_query("SELECT SUM(uploaded) AS uploaded, SUM(seedtime) AS seedtime FROM snatched WHERE torrentid = $torrentid AND userid = $userid")); //计算该用户该种子的上传量和做种时间
			if (($snat['seedtime'] - $row['seedtime']) < ($claimtime * 3600) && ($snat['uploaded'] - $row['uploaded']) < ($torrentsize * $claimmul)) {//如果做种时间小于认领达标时间并且上传量小于认领达标上传量的指定倍数
				//未达标
				if ($torrentsize >= 209715200 && $torrentsize < 10737148240) {//200M以上，10G以下的
					$claimbonus = ($snat['uploaded'] - $row['uploaded']) / 1024 * 0.000015; //每G得15个魔力值
					sql_query("UPDATE users SET seedbonus = seedbonus + $claimbonus WHERE id = $userid");
				} elseif ($torrentsize >= 10737148240 && $torrentsize < 32212254720) {//10G以上，30G以下的
					$claimbonus = ($snat['uploaded'] - $row['uploaded']) / 1024 * 0.00002; //每G得20个魔力值
					sql_query("UPDATE users SET seedbonus = seedbonus + $claimbonus WHERE id = $userid");
				} elseif ($torrentsize >= 32212254720) {//30G以上
					$claimbonus = ($snat['uploaded'] - $row['uploaded']) / 1024 * 0.00003; //每G得30个魔力值
					sql_query("UPDATE users SET seedbonus = seedbonus + $claimbonus WHERE id = $userid");
				}
				$msg = "你认领的种子[b][url=details.php?id=" . $torrentid . "]" . htmlspecialchars($torrent_name) . "[/url][/b]在30天内未达到做种 " . $claimtime . " 小时或上传量为种子(" . mksize($torrentsize) . ")大小的 " . $claimmul . " 倍，因此只能获得每G上传量奖励。上传量：" . mksize($snat['uploaded'] - $row['uploaded']) . "，做种时间：" . mkprettytime($snat['seedtime'] - $row['seedtime']) . "，共 " . round($claimbonus, 3) . " 个魔力值。";
				$subject = "你认领的种子未达到标准";
				$allowedtime = date("Y-m-d H:i:s");
				sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $userid, '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__); //发送站短通知
				if ($row['added'] > $dt) {
					sql_query("UPDATE claim SET seedtime = $snat[seedtime], uploaded = $snat[uploaded] WHERE torrentid = $torrentid AND userid = $userid"); //重置认领未超过30天的认领种子的做种时间和上传量
				} else {
					sql_query("DELETE FROM claim WHERE torrentid = $torrentid AND userid = $userid AND added <= '$dt'"); //释放认领>=30天的认领种子
				}
				writeBonusComment($userid, "因认领种子(" . htmlspecialchars($torrent_name) . ")得到 " . round($claimbonus, 3) . " 个魔力值");
			} else {
				//已达标
				if ($torrentsize >= 209715200 && $torrentsize < 10737148240) {//200M以上，10G以下的
					$claimbonus = 200 + ($snat['uploaded'] - $row['uploaded']) / 1024 * 0.000015; //每G得15个魔力值
					sql_query("UPDATE users SET seedbonus = seedbonus + $claimbonus WHERE id = $userid");
				} elseif ($torrentsize >= 10737148240 && $torrentsize < 32212254720) {//10G以上，30G以下的
					$claimbonus = 400 + ($snat['uploaded'] - $row['uploaded']) / 1024 * 0.00002; //每G得20个魔力值
					sql_query("UPDATE users SET seedbonus = seedbonus + $claimbonus WHERE id = $userid");
				} elseif ($torrentsize >= 32212254720) {//30G以上
					$claimbonus = 600 + ($snat['uploaded'] - $row['uploaded']) / 1024 * 0.00003; //每G得30个魔力值
					sql_query("UPDATE users SET seedbonus = seedbonus + $claimbonus WHERE id = $userid");
				}
				$msg = "你认领的种子[b][url=details.php?id=" . $torrentid . "]" . htmlspecialchars($torrent_name) . "[/url][/b]在30天内达到做种 " . $claimtime . " 小时或上传量为种子(" . mksize($torrentsize) . ")大小的 " . $claimmul . " 倍，因此获得基础奖励+每G上传量奖励。上传量：" . mksize($snat['uploaded'] - $row['uploaded']) . "，做种时间：" . mkprettytime($snat['seedtime'] - $row['seedtime']) . "，共 " . round($claimbonus, 3) . " 个魔力值。";
				$subject = "你认领的种子达到标准";
				$allowedtime = date("Y-m-d H:i:s");
				sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $userid, '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__); //发送站短通知
				sql_query("DELETE FROM claim WHERE torrentid = $torrentid AND userid = $userid"); //释放已达标的种子
				writeBonusComment($userid, "因认领种子(" . htmlspecialchars($torrent_name) . ")得到 " . round($claimbonus, 3) . " 个魔力值");
			}
		}
		sql_query("DELETE FROM claim WHERE torrentid NOT IN (SELECT id FROM torrents)"); //删除不存在或被删除种子的记录
		if ($printProgress) {
			printProgress("结算并清理/重置认领30天及以上的种子");
		}
	}
//等级2更新--结束
//等级3更新--开始  默认3600秒（60分钟）
	$res = sql_query("SELECT value_u FROM avps WHERE arg = 'lastcleantime3'");
	$row = mysql_fetch_array($res);
	if (!$row) {
		sql_query("INSERT INTO avps (arg, value_u, value_i) VALUES ('lastcleantime3', '$now', '$autoclean_interval_three')") or sqlerr(__FILE__, __LINE__);
		return;
	}
	$ts = $row[0];
	if ($ts + $autoclean_interval_three > $now && !$forceAll) {
		return '等级3的清理已完成';
	} else {
		sql_query("UPDATE avps SET value_u = '$now', value_i = '$autoclean_interval_three' WHERE arg = 'lastcleantime3'") or sqlerr(__FILE__, __LINE__);
	}

	$torrents = array();
	$res = sql_query("SELECT torrent, seeder, COUNT(*) AS c FROM peers GROUP BY torrent, seeder") or sqlerr(__FILE__, __LINE__);
	while ($row = mysql_fetch_assoc($res)) {
		if ($row["seeder"] == "yes")
			$key = "seeders";
		else
			$key = "leechers";
		$torrents[$row["torrent"]][$key] = $row["c"];
	}

	$res = sql_query("SELECT torrent, COUNT(*) AS c FROM comments GROUP BY torrent") or sqlerr(__FILE__, __LINE__);
	while ($row = mysql_fetch_assoc($res)) {
		$torrents[$row["torrent"]]["comments"] = $row["c"];
	}

	$fields = explode(":", "comments:leechers:seeders");
	$res = sql_query("SELECT id, seeders, leechers, comments FROM torrents") or sqlerr(__FILE__, __LINE__);
	while ($row = mysql_fetch_assoc($res)) {
		$id = $row["id"];
		$torr = $torrents[$id];
		foreach ($fields as $field) {
			if (!isset($torr[$field]))
				$torr[$field] = 0;
		}
		$update = array();
		foreach ($fields as $field) {
			if ($torr[$field] != $row[$field])
				$update[] = "$field = " . $torr[$field];
		}
		if (count($update))
			sql_query("UPDATE torrents SET " . implode(", ", $update) . " WHERE id = $id") or sqlerr(__FILE__, __LINE__);
	}
	if ($printProgress) {
		printProgress("更新做种、下载、评论数量");
	}

	sql_query("UPDATE users SET noad='no' WHERE noaduntil < " . sqlesc(date("Y-m-d H:i:s")) . ($enablenoad_advertisement == 'yes' ? " AND class < " . sqlesc($noad_advertisement) : ""));
	if ($printProgress) {
		printProgress("判断魔力值购买不显示广告截止日期");
	}

	$forums = sql_query("select id from forums") or sqlerr(__FILE__, __LINE__);
	while ($forum = mysql_fetch_assoc($forums)) {
		$postcount = 0;
		$topiccount = 0;
		$topics = sql_query("select id from topics where forumid=$forum[id]") or sqlerr(__FILE__, __LINE__);
		while ($topic = mysql_fetch_assoc($topics)) {
			$res = sql_query("select count(*) from posts where topicid=$topic[id]") or sqlerr(__FILE__, __LINE__);
			$arr = mysql_fetch_row($res);
			$postcount += $arr[0];
			++$topiccount;
		}
		sql_query("update forums set postcount=$postcount, topiccount=$topiccount where id=$forum[id]") or sqlerr(__FILE__, __LINE__);
	}
	$Cache->delete_value('forums_list');
	if ($printProgress) {
		printProgress("更新论坛主题/帖子数量");
	}
	/*
	  if ($offervotetimeout_main) {
	  $secs = (int) $offervotetimeout_main;
	  $dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - ($offervotetimeout_main))));
	  $res = sql_query("SELECT id, name FROM offers WHERE added < $dt AND allowed <> 'allowed'") or sqlerr(__FILE__, __LINE__);
	  while ($arr = mysql_fetch_assoc($res)) {
	  sql_query("DELETE FROM offers WHERE id=$arr[id]") or sqlerr(__FILE__, __LINE__);
	  sql_query("DELETE FROM offervotes WHERE offerid=$arr[id]") or sqlerr(__FILE__, __LINE__);
	  sql_query("DELETE FROM comments WHERE offer=$arr[id]") or sqlerr(__FILE__, __LINE__);
	  write_log("系统自动清理：Offer $arr[id] ($arr[name]) was deleted by system (vote timeout)", 'normal');
	  }
	  }
	  if ($printProgress) {
	  printProgress("删除候选（无用）");
	  }

	  if ($offeruptimeout_main) {
	  $secs = (int) $offeruptimeout_main;
	  $dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - ($secs))));
	  $res = sql_query("SELECT id, name FROM offers WHERE allowedtime < $dt AND allowed = 'allowed'") or sqlerr(__FILE__, __LINE__);
	  while ($arr = mysql_fetch_assoc($res)) {
	  sql_query("DELETE FROM offers WHERE id=$arr[id]") or sqlerr(__FILE__, __LINE__);
	  sql_query("DELETE FROM offervotes WHERE offerid=$arr[id]") or sqlerr(__FILE__, __LINE__);
	  sql_query("DELETE FROM comments WHERE offer=$arr[id]") or sqlerr(__FILE__, __LINE__);
	  write_log("系统自动清理：Offer $arr[id] ($arr[name]) was deleted by system (upload timeout)", 'normal');
	  }
	  }
	  if ($printProgress) {
	  printProgress("删除候选（无用）");
	  }
	 *
	 */

	$res = sql_query("SELECT * FROM users") or sqlerr(__FILE__, __LINE__);
	while ($arr = mysql_fetch_assoc($res)) {
		$res2 = sql_query("SELECT SUM(seedtime) AS st, SUM(leechtime) AS lt FROM snatched WHERE userid = " . $arr['id'] . " LIMIT 1") or sqlerr(__FILE__, __LINE__);
		$arr2 = mysql_fetch_assoc($res2) or sqlerr(__FILE__, __LINE__);
		sql_query("UPDATE users SET seedtime = " . intval($arr2['st']) . ", leechtime = " . intval($arr2['lt']) . " WHERE id = " . $arr['id']) or sqlerr(__FILE__, __LINE__);
	}
	if ($printProgress) {
		printProgress("更新用户的总做种和下载时间");
	}
//等级3更新--结束
//等级4更新--开始  默认43200秒（12小时）
	$res = sql_query("SELECT value_u FROM avps WHERE arg = 'lastcleantime4'");
	$row = mysql_fetch_array($res);
	if (!$row) {
		sql_query("INSERT INTO avps (arg, value_u, value_i) VALUES ('lastcleantime4', '$now', '$autoclean_interval_four')") or sqlerr(__FILE__, __LINE__);
		return;
	}

	$ts = $row[0];
	if ($ts + $autoclean_interval_four > $now && !$forceAll) {
		return '等级3的清理已完成';
	} else {
		sql_query("UPDATE avps SET value_u = '$now', value_i = '$autoclean_interval_four' WHERE arg = 'lastcleantime4'") or sqlerr(__FILE__, __LINE__);
	}

	//清理新建7天后无内容专辑
	$deltime = sqlesc(date("Y-m-d H:i:s", time() - 86400 * 7));
	sql_query("DELETE FROM album WHERE added < $deltime AND id NOT IN (SELECT DISTINCT albumid FROM albumseries)");
	if ($printProgress) {
		printProgress("清理新建7天后无任何内容的专辑");
	}

	//更新IMDb和豆瓣信息
	$checktime = $memcache->get('checktimes');
	if ((((int) date('H')) >= 3) && (((int) date('H')) <= 4) && ((((int) time()) - $checktime) >= 86400 * 3)) {
		$memcache->set('checktimes', (int) time());
		$resss = sql_query("SELECT url, dburl FROM torrents ORDER BY id DESC LIMIT 50");
	}
	if (mysql_num_rows($resss) > 0) {
		while ($row = mysql_fetch_array($resss)) {
			$imdb_id = parse_imdb_id($row['url']);
			if ($imdb_id) {
				$thenumbers = $imdb_id;
				$movie = new imdb($thenumbers);
				$movieid = $thenumbers;
				$movie->setid($movieid);
				$target = array('Title');
				$movie->purge_single(true);
				set_cachetimestamp($id, "cache_stamp");
				$movie->preparecache($target, true);
				$Cache->delete_value('imdb_id_' . $thenumbers . '_movie_name');
				$Cache->delete_value('imdb_id_' . $thenumbers . '_large', true);
				$Cache->delete_value('imdb_id_' . $thenumbers . '_median', true);
				$Cache->delete_value('imdb_id_' . $thenumbers . '_minor', true);
			}
			$douban_id = parse_douban_id($row['dburl']);
			if ($douban_id) {
				$dbdata = new douban();
				$dbdata->setid($douban_id, "douban");
				set_cachetimestamp($id, "cache_stamp");
			}
		}
		if ($printProgress) {
			printProgress("更新IMDb和豆瓣信息");
		}
	}

	//清除无用的IMDb和豆瓣信息
	$checktimes = $memcache->get('checktimess');
	if ((((int) date('H')) >= 1) && (((int) date('H')) <= 2) && ((((int) time()) - $checktimes) >= 86400 * 7)) {
		$memcache->set('checktimess', (int) time());
		foreach (getDir("imdb/cache") as $key) {
			$imdbrow = basename($key, ".Title");
			$imdbres = sql_query("SELECT id FROM torrents WHERE url = '$imdbrow' OR dburl = '$imdbrow'");
			if (mysql_num_rows($imdbres) == 0) {
				unlink($key);
			}
			$dbrow = basename($key, ".page");
			$dbres = sql_query("SELECT id FROM torrents WHERE url = '$dbrow' OR dburl = '$dbrow'");
			if (mysql_num_rows($dbres) == 0) {
				unlink($key);
			}
		}
		foreach (getDir("imdb/images") as $key) {
			$row = basename($key, ".jpg");
			$res = sql_query("SELECT id FROM torrents WHERE url = '$row' OR dburl = '$row'");
			if (mysql_num_rows($res) == 0) {
				unlink($key);
			}
		}
		if ($printProgress) {
			printProgress("清除无用的IMDb和豆瓣信息");
		}
	}

	//H&R系统
	/*
	 * 正常的种子在发布N天内的种子才会计算H&R
	 * 下载超过种子总体积$hrstartradio%后开始计算H&R
	 * 在应该完成的时间内做种时间或分享率达到要求则不增加H&R
	 */
	if ($hr == 'yes') {
		$checkadded = sqlesc(date("Y-m-d H:i:s", time() - 86400 * 30)); //超过N天的不计算H&R
		$res = sql_query("SELECT id, torrentid, userid, uploaded, downloaded, seedtime, last_action, startdat, completedat, finished, hr FROM snatched WHERE hr = 0 AND torrentid IN (SELECT id FROM torrents WHERE status = 'normal' AND added > $checkadded)") or sqlerr(__FILE__, __LINE__);
		while ($arr = mysql_fetch_assoc($res)) {
			$id = $arr['id'];
			$userid = $arr['userid'];
			$torrentid = $arr['torrentid'];
			$torrent_size_value = mysql_fetch_array(sql_query("SELECT size FROM torrents WHERE id = $torrentid"));
			$torrent_size = $torrent_size_value[0];
			$hr_state_value = mysql_fetch_array(sql_query("SELECT hr_state FROM torrents WHERE id = $torrentid"));
			$hr_state = $hr_state_value[0];
			$singleradio = $arr['uploaded'] / $arr['downloaded'];
			if ($hr_state == "normal") {
				$hr_time = $hrhour * 3600; //做种时间小于$hrhour小时，默认2小时
				$hr_torrent_size = 0; //1 * 1024 * 1024 * 1024; //种子大于1G
				$maxdt = date("Y-m-d H:i:s", (TIMENOW - 86400 * $hrday)); //规定$hrday天之内必须达标，可以将改为其他开始计算H&R的时间，默认7天
			} elseif ($hr_state == "sticky") {
				$hr_time_value = mysql_fetch_array(sql_query("SELECT hr_time FROM torrents WHERE id = $torrentid"));
				$hr_time = $hr_time_value[0];
				$hr_torrent_size = 0;
				$hr_until_value = mysql_fetch_array(sql_query("SELECT hr_until FROM torrents WHERE id = $torrentid"));
				$hr_until = $hr_until_value[0];
				$maxdt = date("Y-m-d H:i:s", (TIMENOW - $hr_until));
			}
			if ($stronghr == 'no') {
				if ($hr_state != "no" && round(($arr['downloaded'] / $torrent_size), 1) >= $hrstartradio / 100) {//如果下载超过种子总体积的$hrstartradio%后，H&R状态!=no的进入检查流程
					if ($torrent_size >= $hr_torrent_size && $arr['seedtime'] < $hr_time && $singleradio < $hrradio) {//如果种子体积≥H&R触发体积，并且做种时间＜H&R要求时间，并且单种分享率＜H&R要求单种分享率，就走H&R检查流程(两个检查条件都不满足才会走流程)
						//两个检查条件都不满足时，完成时间需要＞检查时间，否则就成了都增加H&R了
						if ($arr['completedat'] < $maxdt && $arr['finished'] == 'yes') {//如果完成时间<H&R规定检查天数，并且已经完成，则继续进行检查流程
							$donor_value = mysql_fetch_array(sql_query("SELECT donor FROM users WHERE id = $userid"));
							$donor = $donor_value[0];
							$userclass_value = mysql_fetch_array(sql_query("SELECT class FROM users WHERE id = $userid"));
							$userclass = $userclass_value[0];
							$torrent_name_value = mysql_fetch_array(sql_query("SELECT name FROM torrents WHERE id = $torrentid")); //获取种子名字
							$torrent_name = $torrent_name_value[0];
							sql_query("UPDATE snatched SET hr = 1 WHERE id = $id") or sqlerr(__FILE__, __LINE__); //将snatched里面的HR设置为1，表示未完成H&R要求
							if ($donor == 'no' && $userclass < $hrmanage_class) {//非捐赠用户，并且在H&R规则检查内的用户才会累计H&R数量
								sql_query("UPDATE users SET hr = hr + 1 WHERE id = $userid") or sqlerr(__FILE__, __LINE__); //HR数加1
							}
							if ($hr_state == 'sticky') {
								$msg = "你下载的种子 [b][url=details.php?id=" . $torrentid . "]" . htmlspecialchars($torrent_name) . "[/url][/b] " . ($hr_until / 86400) . " 天内保种时间小于 " . ($hr_time / 60) . " 小时，因此你得到了一个H&R!";
								$subject = "你得到了一个H&R";
								$allowedtime = date("Y-m-d H:i:s");
								//if ($donor == 'no' && $userclass < $hrmanage_class) {//非捐赠用户，并且在H&R规则检查内的，发送H&R邮件
								sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES (0, $arr[userid], '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__); //发送短信通知H&R者
								//}
							} elseif ($hr_state == 'normal') {
								$msg = "你下载的种子 [b][url=details.php?id=" . $torrentid . "]" . htmlspecialchars($torrent_name) . "[/url][/b] " . $hrday . " 天内保种时间小于 " . $hrhour . " 小时，因此你得到了一个H&R!";
								$subject = "你得到了一个H&R";
								$allowedtime = date("Y-m-d H:i:s");
								//if ($donor == 'no' && $userclass < $hrmanage_class) {//非捐赠用户，并且在H&R规则检查内的，发送H&R邮件
								sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES (0, $arr[userid], '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__); //发送短信通知H&R者
								//}
							}
						} else {
							sql_query("UPDATE snatched SET hr = 2 WHERE id = $id") or sqlerr(__FILE__, __LINE__); //将snatched里面的HR设置为2，表示完成H&R要求，不再计算
						}
					} else {
						sql_query("UPDATE snatched SET hr = 2 WHERE id = $id") or sqlerr(__FILE__, __LINE__); //将snatched里面的HR设置为2，表示完成H&R要求，不再计算
					}
				} else {
					sql_query("UPDATE snatched SET hr = 2 WHERE id = $id") or sqlerr(__FILE__, __LINE__); //将snatched里面的HR设置为2，表示完成H&R要求，不再计算
				}
			} else {
				$stronghrdt = date("Y-m-d H:i:s", (TIMENOW - $stronghruntil));
				if ($arr['startdat'] > $stronghrdt && $arr['seedtime'] < $stronghr_time && $singleradio < $stronghr_radio) {//开始时间大于规定时间，且不满足严格H&R检查条件则封禁
					$msg = "你下载的种子 [b][url=details.php?id=" . $torrentid . "]" . htmlspecialchars($torrent_name) . "[/url][/b] " . $stronghruntil / 86400 . " 天内保种时间小于 " . $stronghr_time / 3600 . " 小时，因此你得到了一个H&R!";
					$subject = "你得到了一个H&R";
					$allowedtime = date("Y-m-d H:i:s");
					//if ($donor == 'no' && $userclass < $hrmanage_class) {//非捐赠用户，并且在H&R规则检查内的，发送H&R邮件
					sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES (0, $arr[userid], '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__); //发送短信通知H&R者
					//}
				} else {
					sql_query("UPDATE snatched SET hr = 2 WHERE id = $id") or sqlerr(__FILE__, __LINE__); //将snatched里面的HR设置为2，表示完成H&R要求，不再计算
				}
			}
		}
		if ($printProgress) {
			printProgress("H&R检查");
		}

		/*
		 * 检查已经触发H&R的种子
		 * 做种超过120小时可消除该种的H&R警告
		 * 做种超过240小时可获得消除一次H&R所需的魔力值
		 */
		if ($stronghr == 'no') {
			$res1 = sql_query("SELECT id, torrentid, userid, seedtime FROM snatched WHERE hr = 1 AND torrentid IN (SELECT id FROM torrents WHERE status = 'normal')") or sqlerr(__FILE__, __LINE__);
			$res2 = sql_query("SELECT id, torrentid, userid, seedtime FROM snatched WHERE hr = 3 AND torrentid IN (SELECT id FROM torrents WHERE status = 'normal')") or sqlerr(__FILE__, __LINE__);
			$h120 = 120 * 3600;
			$h360 = 360 * 3600;
			while ($row = mysql_fetch_array($res1)) {
				$id = $row['id'];
				$userid = $row['userid'];
				$seedtime = $row['seedtime'];
				$torrentid = $row['torrentid'];
				$torrent_name_value = mysql_fetch_array(sql_query("SELECT name FROM torrents WHERE id = $torrentid")); //获取种子名字
				$torrent_name = $torrent_name_value[0];
				$res = mysql_fetch_array(sql_query("SELECT hr FROM users WHERE id = $userid"));
				if ($seedtime >= $h120) {
					sql_query("UPDATE snatched SET hr = 3 WHERE id = $id"); //表示由触发H&R后做种消除的种子H&R标记
					if ($res['hr'] > 0) {
						sql_query("UPDATE users SET hr = hr - 1 WHERE id = $userid");
					}
					writeModComment($userid, "因已得H&R种子做种时间超过 " . $h120 / 3600 . " 小时系统自动消除该H&R");
					$msg = "你已得H&R的种子 [b][url=details.php?id=" . $torrentid . "]" . htmlspecialchars($torrent_name) . "[/url][/b] 的累计保种时间超过 " . $h120 / 3600 . " 小时，因此系统消除了该种子得到的H&R警告。如果累计保种时间超过 " . $h360 / 3600 . " 小时，将得到消除一次H&R所需的魔力值作为奖励";
					$subject = "你消除了一个H&R";
					$allowedtime = date("Y-m-d H:i:s");
					sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES (0, $userid, '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__); //发送短信通知H&R者
				}
			}
			while ($row = mysql_fetch_array($res2)) {
				$id = $row['id'];
				$userid = $row['userid'];
				$seedtime = $row['seedtime'];
				$torrentid = $row['torrentid'];
				$torrent_name_value = mysql_fetch_array(sql_query("SELECT name FROM torrents WHERE id = $torrentid")); //获取种子名字
				$torrent_name = $torrent_name_value[0];
				if ($seedtime >= $h360) {
					sql_query("UPDATE snatched SET hr = 2 WHERE id = $id"); //表示已完成H&R
					sql_query("UPDATE users SET seedbonus = seedbonus + $hrbonus WHERE id = $userid");
					writeBonusComment($userid, "因已得H&R种子做种时间超过 " . $h360 / 3600 . " 小时得到 " . $hrbonus . " 个魔力值");
					$msg = "你已得H&R的种子 [b][url=details.php?id=" . $torrentid . "]" . htmlspecialchars($torrent_name) . "[/url][/b] 的累计保种时间超过 " . $h360 / 3600 . " 小时，因此得到消除一次H&R所需的魔力值作为奖励";
					$subject = "你得到了一个H&R做种奖励";
					$allowedtime = date("Y-m-d H:i:s");
					sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES (0, $userid, '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__); //发送短信通知H&R者
				}
			}
			if ($printProgress) {
				printProgress("H&R消除检查");
			}
		}

		/*
		 * 已得H&R数量超过$hrhit
		 * 则消除H&R数量 - ($hrhit -1)个H&R，剩下的让用户手动消除，尽可能保证用户不被H&R封禁
		 */
		if ($stronghr == 'no') {
			$ress = sql_query("SELECT id, username, seedbonus, hr FROM users WHERE enabled = 'yes' AND hr >= $hrhit AND donor = 'no' AND class < $hrmanage_class") or sqlerr(__FILE__, __LINE__); //设置得到多少H&R后被禁用
			if (mysql_num_rows($ress) > 0) {
				while ($arr = mysql_fetch_assoc($ress)) {
					$hrcleantotalnum = $hrhit - 1; //H&R上限-1
					$hrcleannum = $arr['hr'] - $hrcleantotalnum; //要消除的H&R数量，已得H&R减去上限-1
					$hrautobonusclean = $hrbonus * 1.5 * $hrcleannum; //消除H&R所需魔力值
					if ($arr['seedbonus'] < $hrautobonusclean) {
						writecomment($arr[id], "因不满足H&R要求，被禁用");
						record_op_log(0, $arr['id'], $arr['username'], 'ban', '不满足H&R要求');
						sql_query("UPDATE users SET enabled = 'no' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
					} else {
						sql_query("UPDATE users SET seedbonus = seedbonus - $hrautobonusclean, hr = hr - $hrcleannum WHERE id = $arr[id]");
						writeBonusComment($arr['id'], "H&R违规封禁检查时用魔力值抵消，共消耗了 " . $hrautobonusclean . " 个魔力值");
						$msg = "H&R违规检查时，发现你现有魔力值可以抵消足够多的H&R警告用以保证不被封禁，因此系统使用了你 " . $hrautobonusclean . " 个魔力值消除了 " . $hrcleannum . " 个H&R。\n请注意：因为是系统自动消除H&R的行为，所以消除每个H&R时魔力值消耗为手动消除的1.5倍；如果还有剩余H&R请及时的手动清除，系统只自动消除足以保证不被封禁的H&R数量。";
						$subject = "H&R系统自动消除通知";
						$allowedtime = date("Y-m-d H:i:s");
						sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES (0, $arr[id], '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__); //发送短信通知H&R者
					}
				}
			}
		} else {
			$ress = sql_query("SELECT id, username, seedbonus, hr FROM users WHERE enabled = 'yes' AND hr > 2 AND donor = 'no' AND class < $hrmanage_class") or sqlerr(__FILE__, __LINE__); //设置得到多少H&R后被禁用
			if (mysql_num_rows($ress) > 0) {
				while ($arr = mysql_fetch_assoc($ress)) {
					writecomment($arr[id], "因不满足H&R要求，被禁用");
					record_op_log(0, $arr['id'], $arr['username'], 'ban', '不满足H&R要求');
					sql_query("UPDATE users SET enabled = 'no' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
				}
			}
		}
		if ($printProgress) {
			printProgress("禁用不满足H&R要求的用户");
		}
	}

	//新人考核
	if ($newuser == 'yes') {
		$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $kstime * 86400)));
		//需要注意考虑兑换的VIP，字段儿是： vip_added
		$res = sql_query("SELECT id, username, downloaded, uploaded, seedbonus, seedtime, leechtime FROM users WHERE enabled = 'yes' AND newuser = 'yes' AND donor = 'no' AND vip_added = 'no' AND class < $newusermanage_class AND added < $dt") or sqlerr(__FILE__, __LINE__);
		while ($userinfo = mysql_fetch_assoc($res)) {
			$fanum = sql_query("SELECT COUNT(*) FROM users WHERE status = 'normal' AND owner = " . $userinfo['id']);
			if (!empty($fanum)) {
				$fanum = $fanum;
			} else {
				$fanum = 0;
			}
			if (round($userinfo['uploaded'] / $userinfo['downloaded'], 3) < $ra || $userinfo['downloaded'] < $dl || $userinfo['uploaded'] < $ul || $userinfo['seedbonus'] < $sb || $userinfo['seedtime'] < $ultime || $userinfo['leechtime'] < $dltime || round($userinfo['leechtime'] / $userinfo['seedtime'], 3) < $tr || $fanum < $fa) {
				writecomment($userinfo['id'], "因不满足新人考核，被禁用");
				record_op_log(0, $userinfo['id'], $userinfo['username'], 'ban', '帐号未通过新人考核');
				sql_query("UPDATE users SET enabled = 'no', newuser = 'no' WHERE id = '" . $userinfo['id'] . "'") or sqlerr(__FILE__, __LINE__);
			} else {
				$msg = "恭喜通过新人考核，请再接再厉！注意：通过考核后还有24小时的观察期，观察期内仍然需要保持各项考核达标，否则还是会被系统禁用！请注意您的分享率，谨慎在观察期内进行魔力兑换。";
				$subject = "恭喜通过新人考核";
				$allowedtime = date("Y-m-d H:i:s");
				sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $userinfo[id], '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__);
				sql_query("UPDATE users SET newuser = 'no' WHERE id = '" . $userinfo['id'] . "'") or sqlerr(__FILE__, __LINE__);
			}
		}
		if ($printProgress) {
			printProgress("禁用未通过新人考核的账户");
		}
	}

	//自定义考核
	if ($assessment == 'yes') {
		$ks = date("Y-m-d", strtotime($assessmentstart . " + " . $assessmenttime . " days"));
		$res1 = mysql_fetch_array(sql_query("SELECT id FROM users WHERE enabled = 'yes' AND newuser = 'no' AND donor = 'no' AND vip_added = 'no' AND class < $assessmentmanage AND added < '" . date("Y-m-d H:i:s", strtotime($assessmentdate)) . "'"));
		$fanum = sql_query("SELECT COUNT(*) FROM users WHERE owner = " . $res1['id']);
		if (!empty($fanum)) {
			$fanum = $fanum;
		} else {
			$fanum = 0;
		}
		$res2 = sql_query("SELECT id, downloaded, uploaded, seedbonus, seedtime, leechtime FROM users WHERE enabled = 'yes' AND newuser = 'no' AND donor = 'no' AND class < $assessmentmanage AND added < '" . date("Y-m-d H:i:s", strtotime($assessmentdate)) . "'"); //找到注册时间在指定日期之前的所有帐号，即需要考核的帐号
		if ((round((strtotime($ks) - strtotime(date("Y-m-d"))) / 86400)) == $assessmenttime) {//考核时间开始时，记录开始时的所有条件状态
			while ($ex = mysql_fetch_assoc($res2)) {
				sql_query("UPDATE users SET exdownloaded = downloaded, exuploaded = uploaded, exseedbonus = seedbonus, exseedtime = seedtime, exleechtime = leechtime, extorrent = $fanum, exclass = class WHERE id = '" . $ex['id'] . "'") or sqlerr(__FILE__, __LINE__);
			}
		}
		$res3 = sql_query("SELECT id, added, username, (downloaded - exdownloaded) AS downloaded, (uploaded - exuploaded) AS uploaded, (seedbonus - exseedbonus) AS seedbonus, (seedtime - exseedtime) AS seedtime, (leechtime - exleechtime) AS leechtime, ($fanum - extorrent) AS fatorrent FROM users WHERE enabled = 'yes' AND newuser = 'no' AND donor = 'no' AND exclass < $assessmentmanage AND added < '" . date("Y-m-d H:i:s", strtotime($assessmentdate)) . "'"); //匹配出条件符合的，考核期间即使升级到免考等级也无法避免考核
		if ((round((strtotime($ks) - strtotime(date("Y-m-d"))) / 86400)) == 0) {//考核时间结束开始判断各项条件
			while ($userinfo = mysql_fetch_assoc($res3)) {
				if (round($userinfo['uploaded'] / $userinfo['downloaded'], 3) < $assessmentradio || $userinfo['downloaded'] < $assessmentdl || $userinfo['uploaded'] < $assessmentul || $userinfo['seedbonus'] < $assessmentbonus || $userinfo['seedtime'] < $assessmentultime || $userinfo['leechtime'] < $assessmentdltime || round($userinfo['leechtime'] / $userinfo['seedtime'], 3) < $assessmenttr || $userinfo['fatorrent'] < $assessmentfa) {
					writecomment($userinfo['id'], "因不满足" . $assessmentname . "，被禁用");
					record_op_log(0, $userinfo['id'], $userinfo['username'], 'ban', "帐号未通过" . $assessmentname . "");
					sql_query("UPDATE users SET enabled = 'no', asspass = 'yes' WHERE id = '" . $userinfo['id'] . "'") or sqlerr(__FILE__, __LINE__);
				} else {
					$msg = "恭喜通过" . $assessmentname . "，请再接再厉！注意：通过考核后还有24小时的观察期，观察期内仍然需要保持各项考核达标，否则还是会被系统禁用！请注意您的分享率，谨慎在观察期内进行魔力兑换。";
					$subject = "恭喜通过" . $assessmentname . "";
					$allowedtime = date("Y-m-d H:i:s");
					sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $userinfo[id], '" . $allowedtime . "', " . sqlesc($msg) . ", " . sqlesc($subject) . ")") or sqlerr(__FILE__, __LINE__);
					sql_query("UPDATE users SET asspass = 'yes' WHERE id = '" . $userinfo['id'] . "'") or sqlerr(__FILE__, __LINE__);
				}
			}
		}
		if ((round((strtotime($ks) - strtotime(date("Y-m-d H:i:s"))) / 86400)) < 0) {//考核时间过期将asspass改为no，并重置各项数值，以便下次自定义考核
			sql_query("UPDATE users SET asspass = 'no' WHERE asspass = 'yes'") or sqlerr(__FILE__, __LINE__);
			sql_query("UPDATE users SET exdownloaded='', exuploaded='', exseedbonus='', exseedtime='', exleechtime='', extorrent=''") or sqlerr(__FILE__, __LINE__);
		}
		if ($printProgress) {
			printProgress("禁用未通过" . $assessmentname . "的账户");
		}
	}

//清理过期或无可用流量的VPN帐号
	$ress = sql_query("SELECT userinfo.username FROM userinfo INNER JOIN users ON userinfo.firstname = users.username WHERE userinfo.firstname = users.username AND userinfo.email = users.email");
	while ($row = mysql_fetch_array($ress)) {
		$usetraffic = mysql_fetch_array(sql_query("SELECT SUM(acctoutputoctets) AS aout FROM radacct WHERE username = '" . $row['username'] . "'")); //已经使用流量
		$groupname = mysql_fetch_array(sql_query("SELECT groupname FROM radusergroup WHERE username = '" . $row['username'] . "'")); //取出VPN用户所在的用户组
		$totaltraffic = mysql_fetch_array(sql_query("SELECT value FROM radgroupreply WHERE groupname = '" . $groupname['groupname'] . "' AND attribute = 'Max-Monthly-Traffic'")); //全部可用流量
		if ($totaltraffic['value'] - (0 + $usetraffic['aout']) <= 0) {
			sql_query("DELETE FROM radacct WHERE username = '" . $row['username'] . "'");
			sql_query("DELETE FROM userinfo WHERE username = '" . $row['username'] . "'");
			sql_query("DELETE FROM radcheck WHERE username = '" . $row['username'] . "'");
			sql_query("DELETE FROM radusergroup WHERE username = '" . $row['username'] . "'");
		}
	}
	$deltime = sqlesc(date("Y-m-d H:i:s", time() - 86400 * 30));
	$res = sql_query("SELECT userinfo.username FROM userinfo INNER JOIN users ON userinfo.firstname = users.username WHERE userinfo.firstname = users.username AND userinfo.email = users.email AND userinfo.creationdate <= $deltime");
	while ($row = mysql_fetch_array($res)) {
		sql_query("DELETE FROM radacct WHERE username = '" . $row['username'] . "'");
		sql_query("DELETE FROM userinfo WHERE username = '" . $row['username'] . "'");
		sql_query("DELETE FROM radcheck WHERE username = '" . $row['username'] . "'");
		sql_query("DELETE FROM radusergroup WHERE username = '" . $row['username'] . "'");
	}
	if ($printProgress) {
		printProgress("删除过期或无可用流量的VPN帐号");
	}

	$deadtime = time() - $signup_timeout;
	$delres = sql_query("SELECT id, username FROM users WHERE status = 'pending' AND added < FROM_UNIXTIME($deadtime) AND last_login < FROM_UNIXTIME($deadtime) AND last_access < FROM_UNIXTIME($deadtime)");
	while ($userinfo = mysql_fetch_assoc($delres)) {
		record_op_log(0, $userinfo['id'], $userinfo['username'], 'del', '账号验证未通过');
		sql_query("DELETE FROM users WHERE id='" . $userinfo['id'] . "'") or sqlerr(__FILE__, __LINE__);
	}
	if ($printProgress) {
		printProgress("删除未通过验证的账户");
	}

	$secs = $invite_timeout * 24 * 60 * 60;
	$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs)));
	sql_query("DELETE FROM invites WHERE time_invited < $dt") or sqlerr(__FILE__, __LINE__);
	if ($printProgress) {
		printProgress("删除未发布的邀请码");
	}

	sql_query("TRUNCATE TABLE `regimages`") or sqlerr(__FILE__, __LINE__);
	if ($printProgress) {
		printProgress("删除验证码图像");
	}

	$deletetitle = "你在{$SITENAME}的账号将要被删除";
	$body = "你好，你在{$SITENAME}注册的账号 {$userinfo['username']} 已经连续 " . $deletenotransfer_account * 0.8 . " 天未登录，由于你的账号没有产生流量，如果连续 $deletenotransfer_account 天未登录，你的账号将会被删除。\n{$SITENAME}期待您的回归，我们的地址是 $BASEURL";
	$neverdelete_account = ($neverdelete_account <= UC_VIP ? $neverdelete_account : UC_VIP);

	if ($deletenotransfer_account) {
		$secs = $deletenotransfer_account * 24 * 60 * 60;
		$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs)));
		$maxclass = $neverdelete_account;
		if ($mailtouser == 'yes') {
			//发邮件
			$checktime1 = $memcache->get('checktime1');
			if (((((int) time()) - $checktime1) >= $secs * 0.8)) {
				$memcache->set('checktime1', (int) time());
				$secs2 = $secs * 0.8;
				$dt2 = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs2)));
				$delres = sql_query("SELECT id, username, email FROM users WHERE parked='no' AND status='confirmed' AND class < $maxclass AND last_access < $dt2 AND (uploaded = 0 || uploaded = " . sqlesc($iniupload_main) . ") AND downloaded = 0");
				$notransfererr = 0;
				$notransferdone = 0;
				$notransferemail = array();
				while ($userinfo = mysql_fetch_assoc($delres)) {
					if (sent_mail($userinfo['email'], $SITENAME, $SITEEMAIL, change_email_encode(get_langfolder_cookie(), $deletetitle), change_email_encode(get_langfolder_cookie(), $body), '', false, false, '', get_email_encode(get_langfolder_cookie()), 'noerror')) {
						$emailflag = 1;
						$notransferdone++;
					} else {
						$emailflag = 0;
						$notransfererr++;
						continue;
					}
					$notransferemail[] = $userinfo['email'];
					$notransfererr++;
				}
				if (sent_mail($notransferemail[0], $SITENAME, $SITEEMAIL, change_email_encode(get_langfolder_cookie(), $deletetitle), change_email_encode(get_langfolder_cookie(), $body), '', false, true, $notransferemail, get_email_encode(get_langfolder_cookie()), 'noerror'))
					write_log("系统自动发送邮件：给 $notransfererr 位注册后连续 " . $deletenotransfer_account * 0.8 . " 天未登录且无流量用户发送邮件提醒", 'normal');
				else
					write_log("系统自动发送邮件：有 $notransfererr 位无流量用户发送邮件失败！$notransferdone 位成功" . __LINE__, 'normal');
				if ($printProgress) {
					printProgress("给注册后连续 " . $deletenotransfer_account * 0.8 . " 天未登录且无流量用户发送邮件提醒");
				}
			}
		}
		$delres = sql_query("SELECT id, username FROM users WHERE parked='no' AND status='confirmed' AND class < $maxclass AND last_access < $dt AND (uploaded = 0 || uploaded = " . sqlesc($iniupload_main) . ") AND downloaded = 0");
		while ($userinfo = mysql_fetch_assoc($delres)) {
			record_op_log(0, $userinfo['id'], $userinfo['username'], 'del', '无流量账号连续 ' . $deletenotransfer_account . ' 天未登录');
			sql_query("DELETE FROM users WHERE id='" . $userinfo['id'] . "'") or sqlerr(__FILE__, __LINE__);
			sql_query("DELETE FROM claim WHERE userid = " . $userinfo['id']); //清理被删除用户认领信息
			sql_query("DELETE FROM truckmarks WHERE userid = " . $userinfo['id']); //清理被删除用户小货车信息
		}
	}
	if ($printProgress) {
		printProgress("删除无流量连续 " . $deletenotransfer_account . " 天未登录用户");
	}

	if ($deletenotransfertwo_account) {
		$secs = $deletenotransfertwo_account * 24 * 60 * 60;
		$secs2 = $secs * 1.8;
		$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs)));
		$dt2 = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs2)));
		$maxclass = $neverdelete_account;
		if ($mailtouser == 'yes') {
			//发邮件
			$checktime2 = $memcache->get('checktime2');
			if (((((int) time()) - $checktime2) >= $secs * 0.8)) {
				$memcache->set('checktime2', (int) time());
				$notransfererr1 = 0;
				$notransferdone1 = 0;
				$notransferemail1 = array();
				$delres = sql_query("SELECT id, username, email FROM users WHERE  parked='no' AND status='confirmed' AND class < $maxclass AND added < $dt2 AND (uploaded = 0 || uploaded = " . sqlesc($iniupload_main) . ") AND downloaded = 0");
				while ($userinfo = mysql_fetch_assoc($delres)) {
					if (sent_mail($userinfo['email'], $SITENAME, $SITEEMAIL, change_email_encode(get_langfolder_cookie(), $deletetitle), change_email_encode(get_langfolder_cookie(), $body), '', false, false, '', get_email_encode(get_langfolder_cookie()), 'noerror'))
						$emailflag = 1;
					else {
						$notransfererr1++;
						$emailflag = 0;
						continue;
					}
					$notransferemail1[] = $userinfo['email'];
					$notransfererr1++;
				}
				if (sent_mail($notransferemail1[0], $SITENAME, $SITEEMAIL, change_email_encode(get_langfolder_cookie(), $deletetitle), change_email_encode(get_langfolder_cookie(), $body), '', false, true, $notransferemail1, get_email_encode(get_langfolder_cookie()), 'noerror'))
					write_log("系统自动发送邮件：给 $notransfererr1 位注册后连续 " . $deletenotransfertwo_account * 0.8 . " 天未登录且无流量用户发送邮件提醒", 'normal');
				else
					write_log("系统自动发送邮件：有 $notransfererr1 位长时间未登录用户发送邮件失败！$notransferdone1 位成功！！！" . __LINE__, 'normal');
				if ($printProgress) {
					printProgress("给注册后连续 " . $deletenotransfertwo_account * 0.8 . " 天未登录用户发送邮件提醒");
				}
			}
		}
		$delres = sql_query("SELECT id, username FROM users WHERE  parked='no' AND status='confirmed' AND class < $maxclass AND added < $dt AND (uploaded = 0 || uploaded = " . sqlesc($iniupload_main) . ") AND downloaded = 0");
		while ($userinfo = mysql_fetch_assoc($delres)) {
			record_op_log(0, $userinfo['id'], $userinfo['username'], 'del', '注册 ' . $deletenotransfertwo_account . ' 天后仍未产生任何流量');
			sql_query("DELETE FROM users WHERE id='" . $userinfo['id'] . "'") or sqlerr(__FILE__, __LINE__);
			sql_query("DELETE FROM claim WHERE userid = " . $userinfo['id']); //清理被删除用户认领信息
			sql_query("DELETE FROM truckmarks WHERE userid = " . $userinfo['id']); //清理被删除用户小货车信息
		}
		if ($printProgress) {
			printProgress("删除注册 " . $deletenotransfertwo_account . " 天无流量用户");
		}
	}

	if ($deleteunpacked_account) {
		$secs = $deleteunpacked_account * 24 * 60 * 60;
		$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs)));
		$secs2 = $secs * 0.8;
		$dt2 = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs2)));
		$maxclass = $neverdelete_account;
		if ($mailtouser == 'yes') {
			//发邮件
			$checktime3 = $memcache->get('checktime3');
			if (((((int) time()) - $checktime3) >= $secs * 0.8)) {
				$memcache->set('checktime3', (int) time());
				$uppackederrnum = 0;
				$uppackeddonenum = 0;
				$uppackedemail = array();
				$body = "你好，你在{$SITENAME}注册的账号 {$userinfo['username']} 已经连续 " . $deleteunpacked_account * 0.8 . " 天未登录，由于你的账号没有封存，如果连续 $deleteunpacked_account 天未登录，你的账号将会被删除。\n{$SITENAME}期待您的回归，我们的地址是 $BASEURL";
				$delres = sql_query("SELECT id, username, email FROM users WHERE parked='no' AND status='confirmed' AND class < $maxclass AND last_access < $dt2");
				while ($userinfo = mysql_fetch_assoc($delres)) {
					if (sent_mail($userinfo['email'], $SITENAME, $SITEEMAIL, change_email_encode(get_langfolder_cookie(), $deletetitle), change_email_encode(get_langfolder_cookie(), $body), '', false, false, '', get_email_encode(get_langfolder_cookie()), 'noerror')) {
						$emailflag = 1;
						$uppackeddonenum++;
					} else {
						$uppackederrnum++;
						$emailflag = 0;
						continue;
					}
					$uppackedemail[] = $userinfo['email'];
					$uppackederrnum++;
				}
				if (sent_mail($uppackedemail[0], $SITENAME, $SITEEMAIL, change_email_encode(get_langfolder_cookie(), $deletetitle), change_email_encode(get_langfolder_cookie(), $body), '', false, true, $uppackedemail, get_email_encode(get_langfolder_cookie()), 'noerror'))
					write_log("系统自动发送邮件：给 $uppackederrnum 位未封存账号连续 " . $deleteunpacked_account * 0.8 . " 天未登录用户发送邮件提醒", 'normal');
				else
					write_log("系统自动发送邮件：有 $uppackederrnum 位封存长时间未登录用户发送邮件失败！$uppackeddonenum 位成功！！！！" . __LINE__, 'normal');
				if ($printProgress) {
					printProgress("给未封存账号连续 " . $deleteunpacked_account * 0.8 . " 天未登录用户发送邮件提醒");
				}
			}
		}
		$delres = sql_query("SELECT id, username FROM users WHERE parked='no' AND status='confirmed' AND class < $maxclass AND last_access < $dt");
		while ($userinfo = mysql_fetch_assoc($delres)) {
			record_op_log(0, $userinfo['id'], $userinfo['username'], 'del', '未封存账号连续 ' . $deleteunpacked_account . ' 天未登录');
			sql_query("DELETE FROM users WHERE id='" . $userinfo['id'] . "'") or sqlerr(__FILE__, __LINE__);
			sql_query("DELETE FROM claim WHERE userid = " . $userinfo['id']); //清理被删除用户认领信息
			sql_query("DELETE FROM truckmarks WHERE userid = " . $userinfo['id']); //清理被删除用户小货车信息
		}
	}
	if ($printProgress) {
		printProgress("删除未封存长时间未登录用户");
	}

	if ($deletepacked_account) {
		$secs = $deletepacked_account * 24 * 60 * 60;
		$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs)));
		$secs2 = $secs * 0.8;
		$dt2 = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs2)));
		$maxclass = $neverdeletepacked_account;
		if ($mailtouser == 'yes') {
			//发邮件
			$checktime4 = $memcache->get('checktime4');
			if (((((int) time()) - $checktime4) >= $secs * 0.8)) {
				$memcache->set('checktime4', (int) time());
				$packednum = 0;
				$packeddonenum = 0;
				$packedemail[] = array();
				$body = "你好，你在{$SITENAME}注册的账号 {$userinfo[' username']} 已经连续 " . $deletepacked_account * 0.8 . " 天未登录，虽然你的账号已经封存，但是如果连续 $deletepacked_account 天未登录，你的账号仍然会被删除。\n{$SITENAME}期待您的回归，我们的地址是 $BASEURL";
				$delres = sql_query("SELECT id, username, email FROM users WHERE parked='yes' AND status='confirmed' AND class < $maxclass AND last_access < $dt2");
				while ($userinfo = mysql_fetch_assoc($delres)) {
					if (sent_mail($userinfo['email'], $SITENAME, $SITEEMAIL, change_email_encode(get_langfolder_cookie(), $deletetitle), change_email_encode(get_langfolder_cookie(), $body), '', false, false, '', get_email_encode(get_langfolder_cookie()), 'noerror')) {
						$emailflag = 1;
						$packeddonenum++;
					} else {
						$emailflag = 0;
						continue;
					}
					$packednum++;
					$packedemail[] = $userinfo['email'];
				}
				if ($packedemail[0]) {
					if (sent_mail($packedemail[0], $SITENAME, $SITEEMAIL, change_email_encode(get_langfolder_cookie(), $deletetitle), change_email_encode(get_langfolder_cookie(), $body), '', false, true, $packedemail, get_email_encode(get_langfolder_cookie()), 'noerror'))
						write_log("系统自动发送邮件：给 $packednum 位封存账号连续 " . $deletepacked_account * 0.8 . " 天未登录用户发送邮件提醒", 'normal');
					else
						write_log("系统自动发送邮件：有 $packednum 位封存账号发送邮件失败！" . __LINE__, 'normal');
				} else {
					write_log("系统自动发送邮件：给 $packednum 位封存账号连续 " . $deletepacked_account * 0.8 . " 天未登录用户发送邮件提醒", 'normal');
				}
				if ($printProgress) {
					printProgress("给封存账号连续 " . $deletepacked_account * 0.8 . " 天未登录用户发送邮件提醒");
				}
			}
		}
		$delres = sql_query("SELECT id, username FROM users WHERE parked='yes' AND status='confirmed' AND class < $maxclass AND last_access < $dt");
		while ($userinfo = mysql_fetch_assoc($delres)) {
			record_op_log(0, $userinfo['id'], $userinfo['username'], 'del', '封存账号连续 ' . $deletepacked_account . ' 天未登录');
			sql_query("DELETE FROM users WHERE id='" . $userinfo['id'] . "'") or sqlerr(__FILE__, __LINE__);
			sql_query("DELETE FROM claim WHERE userid = " . $userinfo['id']); //清理被删除用户认领信息
			sql_query("DELETE FROM truckmarks WHERE userid = " . $userinfo['id']); //清理被删除用户小货车信息
		}
	}
	if ($printProgress) {
		printProgress("删除长时间未登录的封存用户");
	}

	$res = sql_query("SELECT id, modcomment, tovip FROM users WHERE vip_added = 'yes' AND vip_until < NOW()") or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res) > 0) {
		while ($arr = mysql_fetch_assoc($res)) {
			$dt = sqlesc(date("Y-m-d H:i:s"));
			$subject = sqlesc($lang_cleanup_target[get_user_lang($arr[id])]['msg_vip_status_removed']);
			$msg = sqlesc($lang_cleanup_target[get_user_lang($arr[id])]['msg_vip_status_removed_body']);
			$modcomment = htmlspecialchars($arr["modcomment"]);
			$modcomment = date("Y-m-d") . " - 魔力值兑换的VIP状态被系统解除，原等级为：" . $arr['tovip'] . "\n" . $modcomment;
			$modcom = sqlesc($modcomment);
			sql_query("UPDATE users SET class = '" . $arr['tovip'] . "', vip_added = 'no', vip_until = '0000-00-00 00:00:00', modcomment = $modcom WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
			sql_query("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $arr[id], $dt, $msg, $subject)") or sqlerr(__FILE__, __LINE__);
		}
	}
	if ($printProgress) {
		printProgress("判断购买VIP到期");
	}

	if ($ratioless == 'no') {

		function peasant_to_user($down_floor_gb, $down_roof_gb, $minratio) {
			global $lang_cleanup_target, $ratioless;
			if ($down_floor_gb) {
				$downlimit_floor = $down_floor_gb * 1024 * 1024 * 1024;
				$downlimit_roof = $down_roof_gb * 1024 * 1024 * 1024;
				$res = sql_query("SELECT id FROM users WHERE class = 1 AND downloaded >= $downlimit_floor " . ($downlimit_roof > $down_floor_gb ? " AND downloaded < $downlimit_roof" : "") . " AND uploaded / downloaded >= $minratio") or sqlerr(__FILE__, __LINE__);
				if (mysql_num_rows($res) > 0) {
					$dt = sqlesc(date("Y-m-d H:i:s"));
					while ($arr = mysql_fetch_assoc($res)) {
						if ($ratioless == 'no') {
							$subject = sqlesc($lang_cleanup_target[get_user_lang($arr['id'])]['msg_low_ratio_warning_removed']);
							$msg = sqlesc($lang_cleanup_target[get_user_lang($arr['id'])]['msg_your_ratio_warning_removed']);
							writecomment($arr['id'], "吸血警告被系统解除");
							sql_query("UPDATE users SET class = 2, leechwarn = 'no', leechwarnuntil = '0000-00-00 00:00:00' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
							sql_query("INSERT INTO messages (sender, receiver, added, subject, msg) VALUES(0, $arr[id], $dt, $subject, $msg)") or sqlerr(__FILE__, __LINE__);
						} else {
							sql_query("UPDATE users SET class = 2 WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
						}
					}
				}
			}
		}

		peasant_to_user($psdlfive_account, 0, $psratiofive_account);
		peasant_to_user($psdlfour_account, $psdlfive_account, $psratiofour_account);
		peasant_to_user($psdlthree_account, $psdlfour_account, $psratiothree_account);
		peasant_to_user($psdltwo_account, $psdlthree_account, $psratiotwo_account);
		peasant_to_user($psdlone_account, $psdltwo_account, $psratioone_account);
		if ($printProgress) {
			printProgress($lang_functions['text_peasant'] . "判断升级");
		}

		function promotion($class, $down_floor_gb, $minratio, $time_week, $addinvite = 0) {
			global $lang_cleanup_target;
			$oriclass = $class - 1;

			if ($down_floor_gb) {
				$limit = $down_floor_gb * 1024 * 1024 * 1024;
				$maxdt = date("Y-m-d H:i:s", (TIMENOW - 86400 * 7 * $time_week));
				$res = sql_query("SELECT id, max_class_once FROM users WHERE class = $oriclass AND downloaded >= $limit AND uploaded / downloaded >= $minratio AND added < " . sqlesc($maxdt)) or sqlerr(__FILE__, __LINE__);
				if (mysql_num_rows($res) > 0) {
					$dt = sqlesc(date("Y-m-d H:i:s"));
					while ($arr = mysql_fetch_assoc($res)) {
						$subject = sqlesc($lang_cleanup_target[get_user_lang($arr['id'])]['msg_promoted_to'] . get_user_class_name_zh($class, false, false, false));
						$msg = sqlesc($lang_cleanup_target[get_user_lang($arr['id'])]['msg_now_you_are'] . get_user_class_name_zh($class, false, false, false) . $lang_cleanup_target[get_user_lang($arr['id'])]['msg_see_faq']);
						if ($class <= $arr[max_class_once])
							sql_query("UPDATE users SET class = $class WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
						else
							sql_query("UPDATE users SET class = $class, max_class_once=$class, invites=invites+$addinvite WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);

						sql_query("INSERT INTO messages (sender, receiver, added, subject, msg) VALUES(0, $arr[id], $dt, $subject, $msg)") or sqlerr(__FILE__, __LINE__);
					}
				}
			}
		}

		promotion(UC_POWER_USER, $pudl_account, $puprratio_account, $putime_account, $getInvitesByPromotion_class[UC_POWER_USER]);
		promotion(UC_ELITE_USER, $eudl_account, $euprratio_account, $eutime_account, $getInvitesByPromotion_class[UC_ELITE_USER]);
		promotion(UC_CRAZY_USER, $cudl_account, $cuprratio_account, $cutime_account, $getInvitesByPromotion_class[UC_CRAZY_USER]);
		promotion(UC_INSANE_USER, $iudl_account, $iuprratio_account, $iutime_account, $getInvitesByPromotion_class[UC_INSANE_USER]);
		promotion(UC_VETERAN_USER, $vudl_account, $vuprratio_account, $vutime_account, $getInvitesByPromotion_class[UC_VETERAN_USER]);
		promotion(UC_EXTREME_USER, $exudl_account, $exuprratio_account, $exutime_account, $getInvitesByPromotion_class[UC_EXTREME_USER]);
		promotion(UC_ULTIMATE_USER, $uudl_account, $uuprratio_account, $uutime_account, $getInvitesByPromotion_class[UC_ULTIMATE_USER]);
		promotion(UC_NEXUS_MASTER, $nmdl_account, $nmprratio_account, $nmtime_account, $getInvitesByPromotion_class[UC_NEXUS_MASTER]);
		if ($printProgress) {
			printProgress("升级判定");
		}

		function demotion($class, $deratio) {
			global $lang_cleanup_target;

			$newclass = $class - 1;
			$res = sql_query("SELECT id FROM users WHERE class = $class AND uploaded / downloaded < $deratio") or sqlerr(__FILE__, __LINE__);
			if (mysql_num_rows($res) > 0) {
				$dt = sqlesc(date("Y-m-d H:i:s"));
				while ($arr = mysql_fetch_assoc($res)) {
					$subject = $lang_cleanup_target[get_user_lang($arr['id'])]['msg_demoted_to'] . get_user_class_name_zh($newclass, false, false, false);
					$msg = $lang_cleanup_target[get_user_lang($arr['id'])]['msg_demoted_from'] . get_user_class_name_zh($class, false, false, false) . $lang_cleanup_target[get_user_lang($arr['id'])]['msg_to'] . get_user_class_name_zh($newclass, false, false, false) . $lang_cleanup_target[get_user_lang($arr['id'])]['msg_because_ratio_drop_below'] . $deratio . ".\n";
					sql_query("UPDATE users SET class = $newclass WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
					sql_query("INSERT INTO messages (sender, receiver, added, subject, msg) VALUES(0, $arr[id], $dt, " . sqlesc($subject) . ", " . sqlesc($msg) . ")") or sqlerr(__FILE__, __LINE__);
				}
			}
		}

		demotion(UC_NEXUS_MASTER, $nmderatio_account);
		demotion(UC_ULTIMATE_USER, $uuderatio_account);
		demotion(UC_EXTREME_USER, $exuderatio_account);
		demotion(UC_VETERAN_USER, $vuderatio_account);
		demotion(UC_INSANE_USER, $iuderatio_account);
		demotion(UC_CRAZY_USER, $cuderatio_account);
		demotion(UC_ELITE_USER, $euderatio_account);
		demotion(UC_POWER_USER, $puderatio_account);
		if ($printProgress) {
			printProgress("降级判定");
		}

		function user_to_peasant($down_floor_gb, $minratio) {
			global $lang_cleanup_target;
			global $deletepeasant_account, $ratioless;

			$length = $deletepeasant_account * 86400; // warn users until xxx days
			$until = date("Y-m-d H:i:s", (TIMENOW + $length));
			$downlimit_floor = $down_floor_gb * 1024 * 1024 * 1024;
			$res = sql_query("SELECT id FROM users WHERE class = 2 AND downloaded > $downlimit_floor AND uploaded / downloaded < $minratio") or sqlerr(__FILE__, __LINE__);
			if (mysql_num_rows($res) > 0) {
				$dt = sqlesc(date("Y-m-d H:i:s"));
				while ($arr = mysql_fetch_assoc($res)) {
					if ($ratioless == 'no') {
						$subject = $lang_cleanup_target[get_user_lang($arr['id'])]['msg_demoted_to'] . get_user_class_name_zh(UC_PEASANT, false, false, false);
						$msg = $lang_cleanup_target[get_user_lang($arr['id'])]['msg_must_fix_ratio_within'] . $deletepeasant_account . $lang_cleanup_target[get_user_lang($arr['id'])]['msg_days_or_get_banned'];
						writecomment($arr['id'], "因分享率过低被系统警告");
						sql_query("UPDATE users SET class = 1 , leechwarn = 'yes', leechwarnuntil = " . sqlesc($until) . " WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
						sql_query("INSERT INTO messages (sender, receiver, added, subject, msg) VALUES(0, $arr[id], $dt, " . sqlesc($subject) . ", " . sqlesc($msg) . ")") or sqlerr(__FILE__, __LINE__);
					} else {
						sql_query("UPDATE users SET class = 1 WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
					}
				}
			}
		}

		user_to_peasant($psdlone_account, $psratioone_account);
		user_to_peasant($psdltwo_account, $psratiotwo_account);
		user_to_peasant($psdlthree_account, $psratiothree_account);
		user_to_peasant($psdlfour_account, $psratiofour_account);
		user_to_peasant($psdlfive_account, $psratiofive_account);
		if ($printProgress) {
			printProgress("降级到" . $lang_functions['text_peasant']);
		}

		if ($ratioless == 'no') {
			$length = 1 * 86400;
			$dt = date("Y-m-d H:i:s", (TIMENOW - $length));
			$res = sql_query("SELECT id, seedbonus FROM users WHERE enabled = 'yes' AND leechwarn = 'yes' AND leechwarnuntil < '$dt'") or sqlerr(__FILE__, __LINE__);
			if (mysql_num_rows($res) > 0) {
				while ($arr = mysql_fetch_assoc($res)) {
					if ($arr['seedbonus'] > 0) {
						$addup = $arr['seedbonus'] * 2000000;
						writeBonusComment($arr[id], "即将被封号，系统自动将所有魔力值换成上传量，总计消耗 " . $arr['seedbonus'] . " 魔力值，换成 " . mksize($addup) . " 上传量");
						sql_query("UPDATE users SET uploaded = uploaded + $addup, seedbonus = 0 WHERE id = " . $arr['id']) or sqlerr(__FILE__, __LINE__);
					}
				}
			}
			if ($printProgress) {
				printProgress("系统自动将一天后即将被封号的" . $lang_functions['text_peasant'] . "的所有魔力值换成上传量");
			}

			$dt = sqlesc(date("Y-m-d H:i:s"));
			$res = sql_query("SELECT id, username FROM users WHERE enabled = 'yes' AND leechwarn = 'yes' AND leechwarnuntil < $dt") or sqlerr(__FILE__, __LINE__);
			if (mysql_num_rows($res) > 0) {
				while ($arr = mysql_fetch_assoc($res)) {
					writecomment($arr['id'], "分享率过低警告到期时未改善分享率而被系统封禁");
					record_op_log(0, $arr['id'], $arr['username'], 'ban', '持续未改善分享率');
					sql_query("UPDATE users SET enabled = 'no', leechwarnuntil = '0000-00-00 00:00:00' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
				}
			}
			if ($printProgress) {
				printProgress("禁掉持续未改善分享率的" . $lang_functions['text_peasant']);
			}
		}
	}

	//同时如果被禁言、禁止上传下载的话，一同恢复
	$dt = sqlesc(date("Y-m-d H:i:s"));
	//$res = sql_query("SELECT id, forumpost, uploadpos, downloadpos FROM users WHERE enabled = 'yes' AND warned = 'yes' AND warneduntil < $dt") or sqlerr(__FILE__, __LINE__);
	$res = sql_query("SELECT id, forumpost, uploadpos, downloadpos FROM users WHERE warned = 'yes' AND warneduntil < $dt") or sqlerr(__FILE__, __LINE__);

	if (mysql_num_rows($res) > 0) {
		while ($arr = mysql_fetch_assoc($res)) {
			$subject = $lang_cleanup_target[get_user_lang($arr[id])]['msg_warning_removed'];
			$msg = $lang_cleanup_target[get_user_lang($arr[id])]['msg_your_warning_removed'];
			if ($arr['forumpost'] == 'no') {
				sql_query("UPDATE users SET forumpost = 'yes' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
				$msg .= "。你的禁言同时被解除。";
			}
			if ($arr['uploadpos'] == 'no') {
				sql_query("UPDATE users SET uploadpos = 'yes' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
				$msg .= "。你的禁止上传处罚同时被解除。";
			}
			if ($arr['downloadpos'] == 'no') {
				sql_query("UPDATE users SET downloadpos = 'yes' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
				$msg .= "。你的禁止下载处罚同时被解除。";
			}
			writecomment($arr[id], "警告被系统解除");
			sql_query("UPDATE users SET warned = 'no', warneduntil = '0000-00-00 00:00:00' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
			sql_query("INSERT INTO messages (sender, receiver, added, subject, msg) VALUES (0, $arr[id], $dt, " . sqlesc($subject) . ", " . sqlesc($msg) . ")") or sqlerr(__FILE__, __LINE__);
		}
	}
	if ($printProgress) {
		printProgress("移除警告，同时移除处罚");
	}

	if ($deldeadtorrent_torrent > 0) {
		$length = $deldeadtorrent_torrent * 86400;
		$until = date("Y-m-d H:i:s", (TIMENOW - $length));
		$dt = sqlesc(date("Y-m-d H:i:s"));
		$res = sql_query("SELECT id, name, owner, url, dburl FROM torrents WHERE visible = 'no' AND last_action < " . sqlesc($until) . " AND seeders = 0 AND leechers = 0") or sqlerr(__FILE__, __LINE__);
		while ($arr = mysql_fetch_assoc($res)) {
			deletetorrent($arr['id'], $arr['url'], $arr['dburl']);
			$subject = $lang_cleanup_target[get_user_lang($arr[owner])]['msg_your_torrent_deleted'];
			$msg = $lang_cleanup_target[get_user_lang($arr[owner])]['msg_your_torrent'] . "[i]" . $arr['name'] . "[/i]" . $lang_cleanup_target[get_user_lang($arr[owner])]['msg_was_deleted_because_dead'];
			sql_query("INSERT INTO messages (sender, receiver, added, subject, msg) VALUES(0, $arr[owner], $dt, " . sqlesc($subject) . ", " . sqlesc($msg) . ")") or sqlerr(__FILE__, __LINE__);
			write_log("系统自动清理：系统删除了断种 $arr[id] ($arr[name])", 'normal');
		}
	}
	if ($printProgress) {
		printProgress("清理断种");
	}
//等级4更新--结束
//等级5更新--开始  默认86400（1天）
	$res = sql_query("SELECT value_u FROM avps WHERE arg = 'lastcleantime5'") or sqlerr(__FILE__, __LINE__);
	$row = mysql_fetch_array($res);
	if (!$row) {
		sql_query("INSERT INTO avps (arg, value_u, value_i) VALUES ('lastcleantime5', '$now', '$autoclean_interval_five')") or sqlerr(__FILE__, __LINE__);
		return;
	}
	$ts = $row[0];
	if ($ts + $autoclean_interval_five > $now && !$forceAll) {
		return '等级5的清理已完成';
	} else {
		sql_query("UPDATE avps SET value_u = '$now', value_i = '$autoclean_interval_five' WHERE arg = 'lastcleantime5'") or sqlerr(__FILE__, __LINE__);
	}

	$res = sql_query("SELECT id FROM agent_allowed_family");
	while ($row = mysql_fetch_array($res)) {
		$count = get_row_count("users", "WHERE clientselect = " . sqlesc($row['id']));
		sql_query("UPDATE agent_allowed_family SET hits = " . sqlesc($count) . " WHERE id = " . sqlesc($row['id']));
	}
	if ($printProgress) {
		printProgress("更新允许的客户端列表");
	}

	sql_query("DELETE FROM seckenapi WHERE uid NOT IN (SELECT id FROM users WHERE secken = 'yes')");
	if ($printProgress) {
		printProgress("清除不存在用户的洋葱绑定信息");
	}

	sql_query("DELETE FROM `2048` WHERE uid NOT IN (SELECT id FROM users)");
	if ($printProgress) {
		printProgress("清除不存在用户的2048游戏记录");
	}

	$length = 86400 * 90;
	$until = date("Y-m-d H:i:s", (TIMENOW - $length));
	sql_query("DELETE FROM messages WHERE sender = 0 AND added < " . sqlesc($until));
	if ($printProgress) {
		printProgress("删除旧的系统信息");
	}

	$length = 86400 * 90;
	$until = date("Y-m-d H:i:s", (TIMENOW - $length));
	$postIdHalfYearAgo = 0;
	if ($postIdHalfYearAgo) {
		sql_query("UPDATE users SET last_catchup = " . sqlesc($postIdHalfYearAgo) . " WHERE last_catchup < " . sqlesc($postIdHalfYearAgo))or sqlerr(__FILE__, __LINE__);
		sql_query("DELETE FROM readposts WHERE lastpostread < " . sqlesc($postIdHalfYearAgo))or sqlerr(__FILE__, __LINE__);
	}
	if ($printProgress) {
		printProgress("删除旧的已读信息");
	}

	$length = 86400 * 90;
	$until = date("Y-m-d H:i:s", (TIMENOW - $length));
	sql_query("DELETE FROM iplog WHERE access < " . sqlesc($until));
	if ($printProgress) {
		printProgress("删除旧的IP记录");
	}

	$secs = 86400 * 150;
	$until = date("Y-m-d H:i:s", (TIMENOW - $length));
	sql_query("DELETE FROM sitelog WHERE added < " . sqlesc($until)) or sqlerr(__FILE__, __LINE__);
	if ($printProgress) {
		printProgress("删除旧的日志");
	}

	do {
		$res = sql_query("SELECT id FROM torrents") or sqlerr(__FILE__, __LINE__);
		$ar = array();
		while ($row = mysql_fetch_array($res)) {
			$id = $row[0];
			$ar[$id] = 1;
		}

		if (!count($ar))
			break;

		$dp = @opendir($torrent_dir);
		if (!$dp)
			break;

		$ar2 = array();
		while (($file = readdir($dp)) !== false) {
			if (!preg_match('/^(\d+)\.torrent$/', $file, $m))
				continue;
			$id = $m[1];
			$ar2[$id] = 1;
			if (isset($ar[$id]) && $ar[$id])
				continue;
			$ff = $torrent_dir . "/$file";
			unlink($ff);
		}
		closedir($dp);

		if (!count($ar2))
			break;

		$delids = array();
		foreach (array_keys($ar) as $k) {
			if (isset($ar2[$k]) && $ar2[$k])
				continue;
			$delids[] = $k;
			unset($ar[$k]);
		}
		if (count($delids))
			sql_query("DELETE FROM torrents WHERE id IN (" . join(", ", $delids) . ")") or sqlerr(__FILE__, __LINE__);

		$res = sql_query("SELECT torrent FROM peers GROUP BY torrent") or sqlerr(__FILE__, __LINE__);
		$delids = array();
		while ($row = mysql_fetch_array($res)) {
			$id = $row[0];
			if (isset($ar[$id]) && $ar[$id])
				continue;
			$delids[] = $id;
		}
		if (count($delids))
			sql_query("DELETE FROM peers WHERE torrent IN (" . join(", ", $delids) . ")") or sqlerr(__FILE__, __LINE__);

		$res = sql_query("SELECT torrent FROM files GROUP BY torrent") or sqlerr(__FILE__, __LINE__);
		$delids = array();
		while ($row = mysql_fetch_array($res)) {
			$id = $row[0];
			if ($ar[$id])
				continue;
			$delids[] = $id;
		}
		if (count($delids))
			sql_query("DELETE FROM files WHERE torrent IN (" . join(", ", $delids) . ")") or sqlerr(__FILE__, __LINE__);
	} while (0);
	if ($printProgress) {
		printProgress("删除不存在的种子");
	}

	$secs = 86400 * 150;
	sql_query("UPDATE topics, posts SET topics.locked = 'yes' WHERE topics.lastpost = posts.id AND topics.sticky = 'no' AND UNIX_TIMESTAMP(posts.added) < " . TIMENOW . " - $secs") or sqlerr(__FILE__, __LINE__);

	if ($printProgress) {
		printProgress("锁定长时间无活动帖子");
	}

	$secs = 86400 * 90;
	$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs)));
	sql_query("DELETE FROM reports WHERE dealtwith = 1 AND added < $dt") or sqlerr(__FILE__, __LINE__);
	if ($printProgress) {
		printProgress("删除旧的举报");
	}
//等级5更新--结束
	return '所有清理结束';
}
